文件上传下载2.0

仔细看看咯,跟之前那个版本有所不同,大家可以看看以前的,下面这个是更加方便的版本,可获取当前目录路径进行存储图片

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.chenyi.item.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.chenyi.item.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
* @author ChenYi
* @date 2023年06月11日 22:11
*/
@RestController
@RequestMapping("/file")
public class FileController {

@Value("${server.port}")
private String port;

private static final String ip = "http://localhost";

/**
*
* @author ChenYi
* @date 2023/7/3 17:42
* 文件上传
*/
@PostMapping("/upload")
public Result<?> upload(MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename(); // 获取源文件名称
System.out.println(file);
// 定义文件唯一数值
String flag = IdUtil.fastSimpleUUID();
String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/file/" + flag + "-" +originalFilename; // 获取上传路径
FileUtil.writeBytes(file.getBytes(),rootFilePath); // 写入
return Result.success(ip + ":" + port + "/file/" + flag );
}

/**
*
* @author ChenYi
* @date 2023/7/3 17:42
* 文件下载
*/
@GetMapping("/{flag}")
public void getFiles(@PathVariable String flag, HttpServletResponse response) {
OutputStream os; // 新建一个输出流对象
String basePath = System.getProperty("user.dir") + "/src/main/resources/file/"; // 定于文件上传的根路径
List<String> fileNames = FileUtil.listFileNames(basePath); // 获取所有的文件名称
String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse(""); // 找到跟参数一致的文件
try {
if (StrUtil.isNotEmpty(fileName)) {
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/octet-stream");
byte[] bytes = FileUtil.readBytes(basePath + fileName); // 通过文件的路径读取文件字节流
os = response.getOutputStream(); // 通过输出流返回文件
os.write(bytes);
os.flush();
os.close();
}
} catch (Exception e) {
System.out.println("文件下载失败");
}
}

}