美文网首页JavaEE网络编程篇
17.《JavaEE 学习笔记》Servlet 上传文件

17.《JavaEE 学习笔记》Servlet 上传文件

作者: 一直流浪 | 来源:发表于2022-08-09 10:35 被阅读0次

    参考链接:https://www.runoob.com/servlet/servlet-file-uploading.html

    功能介绍:

    利用 Servlet 和表单提交,选择本地文件上传到服务器。上传的文件可以是文本文件或图像文件或任何文档,不能是文件夹。

    需要引入的 jar 文件:commons-fileupload-1.3.2、commons-io-2.5.jar。

    下载链接:

    将下载好的jar包复制到项目/WebContent/WEB-INF/lib 文件夹下:

    实现代码:

    fileUpload.jsp:文件上传的界面页

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    </head>
    <body>
    <h1>文件上传</h1>
    <form action="/JavaEE17ToolDemo/file-upload-servlet" method="post" enctype="multipart/form-data">
        选择一个文件:
        <input type="file" name="file" value="" />
        <br/>
        <input type="submit" value="上传">
    </form>
    
    </body>
    </html>
    

    FileUploadServlet.java:文件上传处理

    package com.company.project.servlet.fileupload;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    @WebServlet("/file-upload-servlet")
    public class FileUploadServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        // 文件上传的存储路径
        private static final String SAVE_PATH = "file-upload";
    
        // 上传配置
        // 配置内存临界值
        private static final int MEMORY_THRESHOLD = 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
    
        public FileUploadServlet() {
            super();
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // 检测是否为多媒体文件
            if (!ServletFileUpload.isMultipartContent(request)) {
                // 如果不是则停止
                PrintWriter out = response.getWriter();
                out.println("表单必须包含 enctype=multipart/form-data");
                out.flush();
                out.close();
                return;
            }
    
            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
    
            // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
            factory.setSizeThreshold(MEMORY_THRESHOLD);
    
            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 + SAVE_PATH;
    
            // 如果路径不存在则创建
            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 fileItem : formItems) {
                        //处理不在表单的字段
                        if(!fileItem.isFormField()) {
                            String fileName = new File(fileItem.getName()).getName();
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            // 在控制台输出文件的上传路径
                            System.out.println(filePath);
                            // 保存文件到硬盘
                            fileItem.write(storeFile);
                            request.setAttribute("message",
                                "文件上传成功!");
                        }
                    }
                }
    
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                request.setAttribute("message",
                        "错误信息: " + e.getMessage());
            }
    
            //文件上传完成跳转
            request.getServletContext().getRequestDispatcher("/page/UploadMes.jsp").forward(request, response);
        }
    }
    

    UploadMes.jsp:文件传输完成跳转页

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>文件上传结果</title>
    </head>
    <body>
    <center>
        <h2>${message }</h2>
    </center>
    
    </body>
    </html>
    

    效果图:

    相关文章

      网友评论

        本文标题:17.《JavaEE 学习笔记》Servlet 上传文件

        本文链接:https://www.haomeiwen.com/subject/igeqwrtx.html