天天看点

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文件上传

继续阅读