SpringBoot--文件上传

1、导包

  由于使用thymeleaf模板引擎进行页面展示,因此需要导入thymeleaf启动器和web启动器

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>    

2、配置文件

# 禁用 thymeleaf 缓存
#spring:
  thymeleaf:
    cache: false
# 是否支持批量上传   (默认值 true)
  servlet:
    multipart:
      enabled: true
# 上传文件的临时目录 (一般情况下不用特意修改)
      location:
# 上传文件最大为 1M (默认值 1M 根据自身业务自行控制即可)
      max-file-size: 1048576
# 上传请求最大为 10M(默认值10M 根据自身业务自行控制即可)
      max-request-size: 10485760
# 文件大小阈值,当大于这个阈值时将写入到磁盘,否则存在内存中,(默认值0 一般情况下不用特意修改)
      file-size-threshold: 0
# 判断是否要延迟解析文件(相当于懒加载,一般情况下不用特意修改)
      resolve-lazily: false

3、thymeleaf页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>

<h2>单一文件上传示例</h2>
<div>
    <form method="POST" enctype="multipart/form-data" action="/test/upload1">
        <p>
            文件1:<input type="file" name="file"/>
            <input type="submit" value="上传"/>
        </p>
    </form>
</div>

<hr/>
<h2>批量文件上传示例</h2>

<div>
    <form method="POST" enctype="multipart/form-data"
          action="/test/upload2">
        <p>
            文件1:<input type="file" name="file"/>
        </p>
        <p>
            文件2:<input type="file" name="file"/>
        </p>
        <p>
            <input type="submit" value="上传"/>
        </p>
    </form>
</div>

<hr/>
<h2>Base64文件上传</h2>
<div>
    <form method="POST" action="/test/upload3">
        <p>
            BASE64编码:<textarea name="base64" rows="10" cols="80"></textarea>
            <input type="submit" value="上传"/>
        </p>
    </form>
</div>

</body>
</html>

4、Controller

 @GetMapping(value ="/uploadIndex")
    public String uploadIndex(){
        return "upload";
    }

    @PostMapping(value ="/upload1")
    public Map<String, String> upload1(@RequestParam("file") MultipartFile file) throws Exception{
        System.out.println("[文件类型] - [{}]" + file.getContentType());
        System.out.println("[文件名称] - [{}]" + file.getOriginalFilename());
        System.out.println("[文件大小] - [{}]" + file.getSize());
        // TODO 将文件写入到指定目录(具体开发中有可能是将文件写入到云存储/或者指定目录通过 Nginx 进行 gzip 压缩和反向代理,此处只是为了演示故将地址写成本地电脑指定目录)
        file.transferTo(new File("E:\" + file.getOriginalFilename()));
        Map<String, String> result = new HashMap<>(16);
        result.put("contentType", file.getContentType());
        result.put("fileName", file.getOriginalFilename());
        result.put("fileSize", file.getSize() + "");
        return result;
    }


    @PostMapping(value ="/upload2")
    public List<Map<String, String>> upload2(@RequestParam("file") MultipartFile[] files) throws Exception{
        if (files == null || files.length == 0) {
            return null;
        }
        List<Map<String, String>> results = new ArrayList<>();
        for (MultipartFile file : files) {
            // TODO Spring Mvc 提供的写入方式
            file.transferTo(new File("E:\" + file.getOriginalFilename()));
            Map<String, String> map = new HashMap<>(16);
            map.put("contentType", file.getContentType());
            map.put("fileName", file.getOriginalFilename());
            map.put("fileSize", file.getSize() + "");
            results.add(map);
        }
        return results;
    }


    @PostMapping("/upload3")
    @ResponseBody
    public void upload3(String base64) throws Exception {
        // TODO BASE64 方式的 格式和名字需要自己控制(如 png 图片编码后前缀就会是 data:image/png;base64,)
        final File tempFile = new File("F:\app\chapter16\test.jpg");
        // TODO 防止有的传了 data:image/png;base64, 有的没传的情况
        String[] d = base64.split("base64,");
        final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
        FileCopyUtils.copy(bytes, tempFile);

    }

5、测试

http://localhost:8080/test/uploadIndex

原文地址:https://www.cnblogs.com/liconglong/p/11715761.html