天天看點

SpringBoot學習2 - MultipartFile檔案上傳

簡單使用

添加依賴

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
           

application.yml

spring:
  # 檔案的上傳與下載下傳配置
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 50MB
           

測試頁面

<!DOCTYPE html>
<html lang="en" xmlns:th=http://www.thymeleaf.org>
<head>
    <meta charset="UTF-8" >
    <title>Title</title>
</head>
<body>

    <[email protected]{}自動補充目前web項目名 -->
    <form th:action="@{/document}" th:method="post" enctype="multipart/form-data">
        <input type="file" name="header">
        <br>
        <br>
        <input type="submit" value="送出檔案">
    </form>

</body>
</html>
           

控制器

@Controller
@RequestMapping("document")
public class DocumentController {
    
    // 視圖頁面
    @RequestMapping("")
    public String documentUI() {
        return "upload/upload1";
    }
    
    
    // 處理檔案上傳處理
    @PostMapping("")
    @ResponseBody
    public Map<String, Object> documentSave(HttpServletRequest request, MultipartFile mf) throws IOException {

        Map<String, Object> messages = new HashMap<String, Object>();
        messages.put("size", mf.getSize());
        messages.put("contentType", mf.getContentType());
        messages.put("OriginalFilename", mf.getOriginalFilename());


        String path = request.getServletContext().getRealPath("/docu/");

        File file = new File(path);
        if(!file.exists()) {
            file.mkdirs();
        }
        File file2 = new File( path + mf.getOriginalFilename());
        mf.transferTo(file2);
        System.out.println("檔案大小:" + file2.getTotalSpace());
        return messages;
    }

}
           

SpringBoot學習2 - MultipartFile檔案上傳

SpringBoot學習2 - MultipartFile檔案上傳

2. 臨時路徑設定

SpringBoot檔案上傳時有個臨時路徑的

@SpringBootConfiguration
public class MyConfig {

    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation("C:\\Users\\lrc\\Desktop\\測試\\臨時路徑");
        return factory.createMultipartConfig();
    }

}
           

3. 設定上傳的檔案生成臨時路徑的閥值。預設無論上傳多大的檔案都會将上傳的檔案生成臨時檔案

SpringBoot學習2 - MultipartFile檔案上傳

繼續閱讀