配置
在application.yml中添加配置
1 2 3 4 5 6 7 8 9 10 11 12 |
spring: servlet: multipart: enabled: true # 表示是否开启文件上传支持,默认为 true file-size-threshold: 0 # 表示文件写入磁盘的阀值,默认为 0 location: # 表示上传文件的临时保存位置 max-file-size: 1MB # 表示上传的单个文件的最大大小,默认为 1MB max-request-size: 10MB # 表示多文件上传时文件的总大小,默认为 10MB file: upload: url: E:/test # 上传路径 |
SpringBoot更改了不同版本的属性名称
SpringBoot 1.3.x及更早
1 |
multipart.max-file-size |
SpringBoot 1.3.x之后
1 |
spring.http.multipart.max-file-size |
SpringBoot 2.0之后
1 |
spring.servlet.multipart.max-file-size |
文件上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.zmjwdzjl.controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.*; @RestController @RequestMapping("file") @Slf4j public class FileController { @Value("${file.upload.url}") private String uploadFilePath; @PostMapping("/upload") public String httpUpload(@RequestParam("files") MultipartFile files[]) { JSONObject object = new JSONObject(); for(int i=0;i<files.length;i++) { // getOriginalFilename方法获取文件名(带后缀),getName方法获取文件名(不带后缀) String fileName = files[i].getOriginalFilename(); File dest = new File(uploadFilePath +'/'+ fileName); // 判断文件所在目录是否存在,如果不存在就创建对应的目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { // 将文件存放到对应的目录下,如果上传重复的文件不会报错,后上传的文件会覆盖已上传的文件 files[i].transferTo(dest); } catch (Exception e) { log.error("{}",e); object.put("success",2); object.put("result","程序错误,请重新上传"); return object.toString(); } } object.put("success",1); object.put("result","文件上传成功"); return object.toString(); } } |
文件下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
@RequestMapping("/download") public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName) { File file = new File(uploadFilePath +'/'+ fileName); if(!file.exists()) { return "下载文件不存在"; } response.reset(); response.setContentType("application/octet-stream"); response.setCharacterEncoding("utf-8"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment;filename=" + fileName ); try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { byte[] buff = new byte[1024]; OutputStream os = response.getOutputStream(); int i = 0; while ((i = bis.read(buff)) != -1) { os.write(buff, 0, i); os.flush(); } } catch (IOException e) { log.error("{}",e); return "下载失败"; } return "下载成功"; } |
参考文章:http://blog.ncmem.com/wordpress/2023/12/05/springboot%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e4%b8%8b%e8%bd%bd-2/
欢迎入群一起讨论