11. Servlet 文件上传

Servlet 文件上传

Servlet 可以通过 HTML 的 <form> 和 2个第3方库  commons-fileupload、commons-io 来完成,在程序运行时确保这2个依赖库引入到 WEB-INF/lib 中;
以下是这两个库的下载地址:
upload.html
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload File</title>
</head>
<body>
<form method="POST" action="uploadFile" enctype="multipart/form-data">
    <label>Choose File: </label><input type="file" name="file" /><br/>
    <input type="submit" name="submit" value="upload">
</form>
</body>
</html>

UploadFileServlet.java
 
public class UploadFileServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "upload"; //上传保存目录
    private static final int MEMORY_HRESHOLD = 1024 * 1024 * 3 ; //传输内存使用上限 ,超过后将临时文件储存在临时目录中3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40 ;  //文件大小上限 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50 ; //请求大小上限 50MB
    /*上传数据,保存文件*/
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
        //检测文件是否为多媒体上传,如果不是则停止
        if(!ServletFileUpload.isMultipartContent(request)){
            PrintWriter out = response.getWriter();
            out.println("Error: form must include enctype=multipart/form-data");
            out.flush();
            return ;
        }
        //设置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(MEMORY_HRESHOLD);    //设置内存临界值
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));  //设置临时储存目录
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);   //设置文件大小上限
        upload.setSizeMax(MAX_REQUEST_SIZE);   //设置请求大小上限
        upload.setHeaderEncoding("UTF-8");
        //文件上传过程
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIR;  //构造临时路径来储存上传文件
        File uploadDir = new File(uploadPath);
        if(!uploadDir.exists())
            uploadDir.mkdir();
        try{
            @SuppressWarnings("unchecked")
            //解析请求的内容,提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);
            if(formItems != null && formItems.size() > 0){
                for(FileItem item : formItems){   //迭代表单数据
                    if(!item.isFormField()){     //不在表单中的字段,即为上传文件数据所在的FileItem
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        item.write(storeFile);        //保存文件到硬盘
                        request.setAttribute("message","Upload file successfully");
                    }
                }
            }
        }catch(Exception ex){
           request.setAttribute("message","Error: " + ex.getMessage());
        }
        //跳转到 massage.jsp
        request.getServletContext().getRequestDispatcher("/message.jsp").forward(request,response);
    }
}

message.jsp
 
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
    <title>Upload file message</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>uploadFile</servlet-name>
        <servlet-class>control2.UploadFileServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>uploadFile</servlet-name>
        <url-pattern>/uploadFile</url-pattern>
    </servlet-mapping>
</web-app>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值