Spring Boot 使用 ServletFileUpload上傳文件失敗,upload.parseRequest(request)爲空

使用Apache Commons FileUpload組件上傳文件時老是返回null,調試發現ServletFileUpload對象爲空,在Spring Boot中有默認的文件上傳組件,在使用ServletFileUpload時須要關閉Spring Boot的默認配置 ,html

禁用MultipartResolverSpring提供的默認值spring

1.0在配置文件中添加緩存

spring.http.multipart.enabled=false

2.0在配置文件中添加app

spring.servlet.multipart.enabled=false

 

    @RequestMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("進入後臺...");

        // 1.建立DiskFileItemFactory對象,配置緩存用
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        // 2. 建立 ServletFileUpload對象
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

        // 3. 設置文件名稱編碼
        servletFileUpload.setHeaderEncoding("utf-8");

        // 4. 開始解析文件
        // 文件md5獲取的字符串
        String fileMd5 = null;
        // 文件的索引
        String chunk = null;
        try {
            List<FileItem> items = servletFileUpload.parseRequest(new ServletRequestContext(request));
            for (FileItem fileItem : items) {

                if (fileItem.isFormField()) { // >> 普通數據
                    String fieldName = fileItem.getFieldName();
                    if ("info".equals(fieldName)) {
                        String info = fileItem.getString("utf-8");
                        System.out.println("info:" + info);
                    }
                    if ("fileMd5".equals(fieldName)) {
                        fileMd5 = fileItem.getString("utf-8");
                        System.out.println("fileMd5:" + fileMd5);
                    }
                    if ("chunk".equals(fieldName)) {
                        chunk = fileItem.getString("utf-8");
                        System.out.println("chunk:" + chunk);
                    }
                } else {
                    // 若是文件夾沒有建立文件夾
                    File file = new File(serverPath + fileMd5);
                    if (!file.exists()) {
                        boolean result = file.mkdirs();
                        System.out.println(result);
                    }
                    // 保存文件
                    File chunkFile = new File(serverPath + fileMd5 + "/" + chunk);
                    FileUtils.copyInputStreamToFile(fileItem.getInputStream(), chunkFile);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    文件:<input type="file" value="請選擇文件" name="file"/> <br/>
    信息:<input type="text" name="info"/> <br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>
相關文章
相關標籤/搜索