使用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脚本,如何写进度条。

    [root@localhost ~]# cat jindutiao.sh #!/bin/bash #进度条 n=$((/)) N=$((/)) ` do sleep 0.01 [ $(($i%$n)) ...

  2. C语言特点_01

    C语言特点: 1.C语言的32个关键字 auto 局部变量(自动储存) break 无条件退出程序最内层循环 case switch语句中选择项 char 单字节整型数据 const 定义不可更改的常 ...

  3. c++ 计算彩票中奖概率

    操作方法: 输入两个数字,第一个数字是备选总数,第二个数字是选择总数,然后返回中将概率. 可以投注多次,结束的时候返回总的中将概率. #include <iostream> using n ...

  4. 初涉「带权并查集」&&bzoj3376: [Usaco2004 Open]Cube Stacking 方块游戏

    算是挺基础的东西 Description     约翰和贝茜在玩一个方块游戏.编号为1到n的n(1≤n≤30000)个方块正放在地上.每个构成一个立方柱.    游戏开始后,约翰会给贝茜发出P(1≤P ...

  5. gpio/外设/控制器

    1.项目中所有的外设pad都是通过GPIO与控制器相连的.比如FSHC<=>gpio<=>flash 2.gpio类似多个 mux 集合. 3.对于与gpio相连的pad具体结 ...

  6. Elasticsearchs的安装/laravel-scout和laravel-scout-elastic的安装

    安装: https://github.com/medcl/elasticsearch-rtf 先下载包 下载解压后 cd elasticsearch-rtf-master ll bin/elastic ...

  7. Ajax四步操作

    第一步得到(XMLHttpRequest)function creatXMLHttpRequest(){ try{ return new XMLHttpRequest(); } catch(e){ t ...

  8. progit 学习笔记-- 1 第一章 第二章

    * 1 起步**  关于版本控制*** 什么是版本控制?记录文件变化,查阅特定版本,回溯到之前的状态.任何类型的文件进行版本控制.复制整个目录 加上备份时间 简单 混淆 无法恢复本地版本控制 数据库记 ...

  9. C#显示及隐藏任务栏

    private const int SW_HIDE = 0; //隐藏任务栏 private const int SW_RESTORE = 9;//显示任务栏 [DllImport("use ...

  10. thymeleaf和artTemplate

    Company最近项目中使用了两个模板引擎,分别是Java服务器端的模板引擎Thymeleaf和前端的模板引擎artTemplate, 其实对于这两个模板引擎 理论上应该是不应该放在一起记录的,但是b ...