SpringBoot实现文件上传下载

配置

在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 

文件下载

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 "下载成功";
}

你可能感兴趣的:(#,SpringBoot,spring,boot,java,spring)