• 文件上传


    概述

    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>
    

    JSP

    <form action="${pageContext.request.contextPath}/fileUpload" enctype="multipart/form-data" method="post">
        <input type="file" name="file"> <br/>
        <input type="submit" value="上传">
    </form>
    

    代码

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY    = "/WEB-INF/upload";
    
    // 上传配置
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
    
        // 创建上传文件的保存目录,建议在WEB-INF路径下
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
    
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置文件最大上传大小
        upload.setFileSizeMax(MAX_FILE_SIZE);
        // 中文处理
        upload.setHeaderEncoding("UTF-8");
        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);
    
        try {
            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);
    
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        request.setAttribute("message","文件上传成功!");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message","错误信息: " + ex.getMessage());
        }
        // 跳转到 message.jsp
        request.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
    }
    
  • 相关阅读:
    MongoDB入门(1)--安装配置
    数据结构课程设计--平衡二叉树
    站立会议
    NABCD
    返回最大子数和(首位相连)
    返回一个数组中的最大子数组和
    最大数组BT
    最大数组
    时间记录日志
    四则运算的问题
  • 原文地址:https://www.cnblogs.com/shenleg/p/14274834.html
Copyright © 2020-2023  润新知