使用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. java mongodb 增删改查 工具类

    package com.jttx.demo;   import com.mongodb.*; import com.mongodb.util.JSON;   import java.net.Unkno ...

  2. javase(3)_二叉树

    // 1.求二叉树中的节点个数 // 2.求二叉树的深度 // 3.前序遍历,中序遍历,后序遍历 // 4.分层遍历二叉树(按层次从上往下,从左往右) // 5.将二叉查找树变为有序的双向链表 // ...

  3. ios 检查内存泄露

    简介 在IPhone程式开发中,记忆体泄漏(内存泄漏)是个很容易发生的情况,因为IPhone必须自行作记忆体管理.现在的开发者,大多习惯用的.NET或Java的等有垃圾回收机制的开发语言来作开发,因此 ...

  4. path.join()与path.resolve()区别

    1.path.resolve([...paths]) path.resolve() 方法会把一个路径或路径片段的序列解析为一个绝对路径. 给定的路径的序列是从右往左被处理的,后面每个 path 被依次 ...

  5. bzoj5183 [Baltic2016]Park

    题目描述: bz luogu 题解: 把坐标系看反了持续$WA$系列. 对偶图+并查集维护. 先处理出树对树.树对墙的空隙,然后把人和空隙按从小到大排序. 用并查集维护四面墙之间是否能互相隔断. 代码 ...

  6. 初涉树形dp

    算是一个……复习以及进阶? 什么是树形dp 树形dp是一种奇妙的dp…… 它的一个重要拓展是和各种树形的数据结构结合,比如说在trie上.自动机上的dp. 而且有些时候还可以拓展到环加外向树.仙人掌上 ...

  7. 【IDE_PyCharm】PyCharm中配置当鼠标悬停时快速提示方法参数

    方法一:通过在settings里面设置当鼠标至于方法之上时给出快速提示 方法二:按住Ctrl键,光标放在任意变量或方法上都会弹出该变量或方法的详细信息,点击鼠标还能跳转到变量或方法的定义处

  8. kvm虚拟迁移

    1. 虚拟迁移 迁移: 系统的迁移是指把源主机上的操作系统和应用程序移动到目的主机,并且能够在目的主机上正常运行.在没有虚拟机的时代,物理机之间的迁移依靠的是系统备份和恢复技术.在源主机上实时备份操作 ...

  9. verilog behavioral modeling--procedural continous assignment(不用)

    assign / deassgin force /release the procedural continuous assignments(using keywords assign and for ...

  10. Web框架之Django_09 重要组件(Django中间件、csrf跨站请求伪造)

    摘要 Django中间件 csrf跨站请求伪造 一.Django中间件: 什么是中间件? 官方的说法:中间件是一个用来处理Django的请求和响应的框架级别的钩子.它是一个轻量.低级别的插件系统,用于 ...