11. Servlet 文件上传

来源:互联网 发布:网络电缆 编辑:程序博客网 时间:2024/06/05 14:15
Servlet 文件上传

Servlet 可以通过 HTML 的 <form> 和 2个第3方库 commons-fileupload、commons-io 来完成,在程序运行时确保这2个依赖库引入到 WEB-INF/lib 中;
以下是这两个库的下载地址:
http://commons.apache.org/proper/commons-fileupload/
http://commons.apache.org/proper/commons-io/

以下是简单的完整示例:
upload.html

UploadFileServlet.java
1
public class UploadFileServlet extends HttpServlet {
2
3
    private static final String UPLOAD_DIR = "upload"; //上传保存目录
4
    private static final int MEMORY_HRESHOLD = 1024 * 1024 * 3 ; //传输内存使用上限 ,超过后将临时文件储存在临时目录中3MB
5
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40 ;  //文件大小上限 40MB
6
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50 ; //请求大小上限 50MB
7
8
    /*上传数据,保存文件*/
9
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
10
11
        //检测文件是否为多媒体上传,如果不是则停止
12
        if(!ServletFileUpload.isMultipartContent(request)){
13
            PrintWriter out = response.getWriter();
14
            out.println("Error: form must include enctype=multipart/form-data");
15
            out.flush();
16
            return ;
17
        }
18
        //设置上传参数
19
        DiskFileItemFactory factory = new DiskFileItemFactory();
20
        factory.setSizeThreshold(MEMORY_HRESHOLD);    //设置内存临界值
21
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));  //设置临时储存目录
22
23
        ServletFileUpload upload = new ServletFileUpload(factory);
24
        upload.setFileSizeMax(MAX_FILE_SIZE);   //设置文件大小上限
25
        upload.setSizeMax(MAX_REQUEST_SIZE);   //设置请求大小上限
26
        upload.setHeaderEncoding("UTF-8");
27
28
        //文件上传过程
29
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIR;  //构造临时路径来储存上传文件
30
        File uploadDir = new File(uploadPath);
31
        if(!uploadDir.exists())
32
            uploadDir.mkdir();
33
        try{
34
            @SuppressWarnings("unchecked")
35
            //解析请求的内容,提取文件数据
36
            List<FileItem> formItems = upload.parseRequest(request);
37
            if(formItems != null && formItems.size() > 0){
38
                for(FileItem item : formItems){   //迭代表单数据
39
                    if(!item.isFormField()){     //不在表单中的字段,即为上传文件数据所在的FileItem
40
                        String fileName = new File(item.getName()).getName();
41
                        String filePath = uploadPath + File.separator + fileName;
42
                        File storeFile = new File(filePath);
43
                        item.write(storeFile);        //保存文件到硬盘
44
                        request.setAttribute("message","Upload file successfully");
45
                    }
46
                }
47
            }
48
        }catch(Exception ex){
49
           request.setAttribute("message","Error: " + ex.getMessage());
50
        }
51
        //跳转到 massage.jsp
52
        request.getServletContext().getRequestDispatcher("/message.jsp").forward(request,response);
53
54
    }
55
}
56

message.jsp

web.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
3
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
5
         version="3.1">
6
    <servlet>
7
        <servlet-name>uploadFile</servlet-name>
8
        <servlet-class>control2.UploadFileServlet</servlet-class>
9
    </servlet>
10
    <servlet-mapping>
11
        <servlet-name>uploadFile</servlet-name>
12
        <url-pattern>/uploadFile</url-pattern>
13
    </servlet-mapping>
14
</web-app>




原创粉丝点击