使用JSP/Servlet简单实现文件上传与下载

jsp上传页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <title>文件上传</title> 
     
    <meta http-equiv="pragma" content="no-cache"> 
    <meta http-equiv="cache-control" content="no-cache"> 
    <meta http-equiv="expires" content="0"> 
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    --> 
 
  </head> 
   
  <body> 
    <form action="${pageContext.request.contextPath}/servlet/UploadServlet" method="post" enctype="multipart/form-data"> 
        name:<input name="name"/><br/> 
        file1:<input type="file" name="f1"/><br/> 
         
        <input type="submit" value="上传"> 
    </form> 
  </body> 
</html>

上传servlet:

public class UploadServlet extends HttpServlet { 
 
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        request.setCharacterEncoding("UTF-8"); 
        response.setContentType("text/html;charset=UTF-8"); 
        PrintWriter out = response.getWriter(); 
        System.out.print(request.getRemoteAddr()); 
        boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
        if(!isMultipart){ 
            throw new RuntimeException("请检查您的表单的enctype属性,确定是multipart/form-data"); 
        } 
        DiskFileItemFactory dfif = new DiskFileItemFactory(); 
        ServletFileUpload parser = new ServletFileUpload(dfif); 
         
        parser.setFileSizeMax(3*1024*1024);//设置单个文件上传的大小 
        parser.setSizeMax(6*1024*1024);//多文件上传时总大小限制 
         
        List<FileItem> items = null; 
        try { 
            items = parser.parseRequest(request); 
        }catch(FileUploadBase.FileSizeLimitExceededException e) { 
            out.write("上传文件超出了3M"); 
            return; 
        }catch(FileUploadBase.SizeLimitExceededException e){ 
            out.write("总文件超出了6M"); 
            return; 
        }catch (FileUploadException e) { 
            e.printStackTrace(); 
            throw new RuntimeException("解析上传内容失败,请重新试一下"); 
        } 
         
        //处理请求内容 
        if(items!=null){ 
            for(FileItem item:items){ 
                if(item.isFormField()){
processFormField(item);
}else{ 
                    processUploadField(item); 
                } 
            } 
        } 
         
        out.write("上传成功!"); 
    } 
    private void processUploadField(FileItem item) { 
        try { 
            String fileName = item.getName(); 
             
             
            //用户没有选择上传文件时 
            if(fileName!=null&&!fileName.equals("")){ 
                fileName = UUID.randomUUID().toString()+"_"+FilenameUtils.getName(fileName); 
                 
                //扩展名 
                String extension = FilenameUtils.getExtension(fileName); 
                //MIME类型 
                String contentType = item.getContentType(); 
                 
                 
                 
                //分目录存储:日期解决 
    //          Date now = new Date(); 
    //          DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
    //           
    //          String childDirectory  = df.format(now); 
                 
                 
                //按照文件名的hashCode计算存储目录 
                String childDirectory = makeChildDirectory(getServletContext().getRealPath("/WEB-INF/files/"),fileName); 
                 
                String storeDirectoryPath = getServletContext().getRealPath("/WEB-INF/files/"+childDirectory); 
                File storeDirectory = new File(storeDirectoryPath); 
                if(!storeDirectory.exists()){ 
                    storeDirectory.mkdirs(); 
                } 
                System.out.println(fileName); 
                item.write(new File(storeDirectoryPath+File.separator+fileName));//删除临时文件 
                 
            } 
        } catch (Exception e) { 
            throw new RuntimeException("上传失败,请重试"); 
        } 
         
    } 
    //计算存放的子目录 
    private String makeChildDirectory(String realPath, String fileName) { 
        int hashCode = fileName.hashCode(); 
        int dir1 = hashCode&0xf;// 取1~4位 
        int dir2 = (hashCode&0xf0)>>4;//取5~8位 
         
        String directory = ""+dir1+File.separator+dir2; 
        File file = new File(realPath,directory); 
        if(!file.exists()) 
            file.mkdirs(); 
         
        return directory; 
    } 
    private void processFormField(FileItem item) { 
        String fieldName = item.getFieldName();//字段名 
        String fieldValue; 
        try { 
            fieldValue = item.getString("UTF-8"); 
        } catch (UnsupportedEncodingException e) { 
            throw new RuntimeException("不支持UTF-8编码"); 
        } 
        System.out.println(fieldName+"="+fieldValue); 
    } 
 
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        doGet(request, response); 
    } 
 
}

显示所有文件的servlet:

public class ShowAllFilesServlet extends HttpServlet { 
 
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        String storeDirectory = getServletContext().getRealPath("/WEB-INF/files"); 
        File root = new File(storeDirectory); 
         
        //用Map保存递归的文件名:key:UUID文件名   value:老文件名 
        Map<String, String> map = new HashMap<String, String>(); 
        treeWalk(root,map); 
         
        request.setAttribute("map", map); 
        request.getRequestDispatcher("/listFiles.jsp").forward(request, response); 
    } 
    //递归,把文件名放到Map中 
    private void treeWalk(File root, Map<String, String> map) { 
        if(root.isFile()){ 
            String fileName = root.getName();//文件名      
            String oldFileName = fileName.substring(fileName.indexOf("_")+1); 
            map.put(fileName, oldFileName); 
        }else{ 
            File fs[] = root.listFiles(); 
            for(File file:fs){ 
                treeWalk(file, map); 
            } 
        } 
         
    } 
 
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        doGet(request, response); 
    } 
 
}

显示所有文件的jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <title>title</title> 
     
    <meta http-equiv="pragma" content="no-cache"> 
    <meta http-equiv="cache-control" content="no-cache"> 
    <meta http-equiv="expires" content="0"> 
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    --> 
 
  </head> 
   
  <body> 
    <h1>以下资源可供下载</h1> 
    <c:forEach items="${map}" var="me"> 
        <c:url value="/servlet/DownloadServlet" var="url"> 
            <c:param name="filename" value="${me.key}"></c:param> 
        </c:url> 
        ${me.value}  <a href="${url}">下载</a><br/> 
    </c:forEach> 
  </body> 
</html>

下载文件的servlet:

public class DownloadServlet extends HttpServlet { 
 
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        String uuidfilename = request.getParameter("filename");//get方式提交的 
        uuidfilename = new String(uuidfilename.getBytes("ISO-8859-1"),"UTF-8");//UUID的文件名 
         
        String storeDirectory = getServletContext().getRealPath("/WEB-INF/files"); 
        //得到存放的子目录 
        String childDirecotry = makeChildDirectory(storeDirectory, uuidfilename); 
         
        //构建输入流 
        InputStream in = new FileInputStream(storeDirectory+File.separator+childDirecotry+File.separator+uuidfilename); 
        //下载 
String oldfilename = uuidfilename.substring(uuidfilename.indexOf("_")+1); 
        //通知客户端以下载的方式打开 
        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(oldfilename, "UTF-8")); 
         
        OutputStream out = response.getOutputStream(); 
         
        int len = -1; 
        byte b[] = new byte[1024]; 
        while((len=in.read(b))!=-1){ 
            out.write(b,0,len); 
        } 
        in.close(); 
        out.close(); 
         
    } 
 
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        doGet(request, response); 
    } 
    //计算存放的子目录 
    private String makeChildDirectory(String realPath, String fileName) { 
        int hashCode = fileName.hashCode(); 
        int dir1 = hashCode&0xf;// 取1~4位 
        int dir2 = (hashCode&0xf0)>>4;//取5~8位 
         
        String directory = ""+dir1+File.separator+dir2; 
        File file = new File(realPath,directory); 
        if(!file.exists()) 
            file.mkdirs(); 
         
        return directory; 
    } 
}

转载:http://www.cnblogs.com/ys-wuhan/p/5772426.html

jsp/servlet实现简单上传和下载的更多相关文章

  1. Jsp/Servlet文件的上传和下载

    文件上传的入门 文件上传的步骤:       总结实现思路: 1.创建核心上传类ServletFileUpload,这个时候需要一个工厂类 2.创建磁盘工厂类对象DiskFileItemFactory ...

  2. jsp+servlet实现文件上传下载

    相关素材下载 01.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" ...

  3. secureCRT简单上传、下载文件记录

    secureCRT简单上传.下载文件记录: 1)sz下载 -y 覆盖 2)rz上传 -y 覆盖 3)以上两个命令属于安装时包含在“Dial-up Networking Support"组中 ...

  4. JSP实现大文件上传和下载

    javaweb上传文件 上传文件的jsp中的部分 上传文件同样可以使用form表单向后端发请求,也可以使用 ajax向后端发请求 1.通过form表单向后端发送请求 <form id=" ...

  5. Servlet实现文件上传和下载

    对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具commo ...

  6. JSP中文件的上传于下载演示样例

    一.文件上传的原理     1.文件上传的前提:         a.form表单的method必须是post         b.form表单的enctype必须是multipart/form-da ...

  7. .Net简单上传与下载

    上传: 首先上传我们需要一个控件-FileUpLoad: 再加上一个上传按钮: 在上传按钮的Click事件中添加如下代码: FileUpload1.SaveAs(Server.MapPath(&quo ...

  8. 通过JSP+servlet实现文件上传功能

    在TCP/IP中,最早出现的文件上传机制是FTP.它将文件由客户端到服务器的标准机制. 但是在JSP中不能使用FTP来上传文件,这是有JSP的运行机制所决定的. 通过为表单元素设置Method=&qu ...

  9. jsp+servlet实现文件上传

    上传(上传不能使用BaseServlet) 1. 上传对表单限制 * method="post" * enctype="multipart/form-data" ...

随机推荐

  1. shell脚本,按空格开始60秒的倒计时。

    [root@localhost wyb]# cat space.sh #!/bin/bash #按空格开始60秒的倒计时#-n表示接受字符的数量,1表示只接受一个字符  a() { - ` do ec ...

  2. WYS APP

    UI图:http://modao.io/app/H8eZCQdV1pskjQ7z8bLh 四个tab:我要赛.赛事.运动吧.个人中心 赛事页面 1.主要是个NavigationController 2 ...

  3. 使用iptables缓解DDOS及CC攻击

    使用iptables缓解DDOS及CC攻击 LINUX  追马  7个月前 (02-09)  465浏览  0评论 缓解DDOS攻击 防止SYN攻击,轻量级预防 iptables -N syn-flo ...

  4. ECshop二次开发 ECSHOP首页显示积分商城里的商品

    以ECSHOP2.7.2官方默认模板为基础 1).首先打开 index.php 文件,在最末尾增加下面函数,注意千万不要写到 “?>” 的外面去,要加在“?>”的前面,加以下代码: /** ...

  5. IE10无法识别setPrototypeOf属性问题

    项目遇到一个需求,React16.6.0兼容IE10浏览器 首先在IE浏览器打开,IE11可以支持,打开控制台切换到IE10,页面白屏,控制台报错. 控制台报错 vue2.0 兼容ie9及其以上 Ma ...

  6. fshc之请求仲裁机制的代码分析

    always@(posedge spi_clk or negedge spiclk_rst_n) begin if(~spiclk_rst_n) arbiter2cache_ack_r <='b ...

  7. i.mx53开发的一些问题

    i.mx53开发的一些问题 转载于此:http://blog.csdn.net/shell_albert/article/details/8242288   原来i.mx53上4GB的Nand Fla ...

  8. JSTL 配置

    pache Tomcat安装JSTL 库步骤如下: 从Apache的标准标签库中下载的二进包(jakarta-taglibs-standard-current.zip). 官方下载地址:http:// ...

  9. python模拟浏览器webdriver登陆网站后抓取页面并输出

    关键在于以下两行代码 特别是find_element_by_xpath写法 很多写成 findElementsByXpath不知道是写错了 还是高级版本是这么写的... #webElement = s ...

  10. sql server 2008启动时:已成功与服务器建立连接,但是在登录过程中发生错误。(provider:命名管道提供程序,error:0-管道的另一端上无任何进程。)(Microsoft SQL Server,错误:233) 然后再连接:错误:18456

    问题:sql server 2008启动时:已成功与服务器建立连接,但是在登录过程中发生错误.(provider:命名管道提供程序,error:0-管道的另一端上无任何进程.)(Microsoft S ...