文件上传和下载

8/24/2023

# 文件上传处理

@RequestMapping("file")
@RestController
public class FileController {

    @Value("${mini-project.path}")
    private String filepath;

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    @PostMapping("upload")
    public Result upload(MultipartFile[] files) {
        try {
            for (MultipartFile file : files) {
                String filename = file.getOriginalFilename();
                if (Objects.isNull(filename)) {
                    throw new RuntimeException("文件名不存在");
                }
                int lastIdx = filename.lastIndexOf('.');
                String suffix;
                if (lastIdx < 0) {
                    suffix = "";
                } else {
                    suffix = filename.substring(lastIdx);
                }
                String prefix = LocalDateTime.now().format(formatter);
                File saveFile = new File(filepath + File.separator + prefix + suffix);
                file.transferTo(saveFile);
            }
            System.out.println(filepath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(200L, "操作成功", null);
    }

    @GetMapping("download")
    public void download(HttpServletResponse response) {
        File file = new File(filepath + File.separator + "default.cur");

        try (
                FileInputStream is = new FileInputStream(file);
                ServletOutputStream os = response.getOutputStream();) {
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=cursor.cur");
            IoUtil.copy(is, os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
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
42
43
44
45
46
47
48
49
50
51

# 前端处理

<form>
    <input id="file" type="file" name="file"/>
    <button id="btn">submit</button>
</form>
1
2
3
4
const btn = document.querySelector("#btn");
const file = document.querySelector("#file");

btn.addEventListener("click", async function (e) {
    
    // 阻止默认事件, 不加改行代码页面将会刷新
    e.preventDefault();
    const data = new FormData();
    
    // 可以添加多个文件, 共用一个key,后台用数组接收
    data.append("files", file.files[0]);
    // data.append("files", file.files[0]);

    const resp = await fetch("http://localhost:8080/file/upload", {
        method: "post",
        body: data
    })

    resp.json().then(res => {
        console.log(res);
    })

});


// file.addEventListener("change", async function (e) {
//     console.log(file.files);
// })
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

# 文件上传参数配置

spring:
  servlet:
    multipart:
      max-file-size: 1024MB # 单个文件大小
      max-request-size: 10240MB # 总文件大小(允许存储文件的文件夹大小)
1
2
3
4
5