Springboot和axios实现文件上传到本地
Sunday 2023/11/22 SpringBoot
# Springboot和axios实现文件上传到本地
# 1. 后端
# 1.1 代码实现
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${ip:localhost}") //拿到配置文件的ip ,冒号后面是默认值
String ip;
@Value("${server.port}")
String port;
private static String ROOT_PATH = System.getProperty("user.dir") +File.separator + "files";//项目根目录 + 文件的存储目录
@PostMapping("/upload")
public Result upload(MultipartFile file) throws IOException {
String originFilename = file.getOriginalFilename(); //获取文件的原始名称
String suffix = StringUtils.getFilenameExtension(originFilename); //获取后缀名,使用的是Spring的工具类
String filename = StringUtils.getFilename(originFilename); //获取文件名,带后缀
String fileRealPath = ROOT_PATH+File.separator+originFilename; // 包括文件名的完整路径
File saveFile = new File(fileRealPath); //文件对象,需要传入一个路径
//判断父路径存不存在,也就是filePath是否存在,如果不存在则创建一个
if(!saveFile.getParentFile().exists()){
saveFile.getParentFile().mkdir();
}
//如果文件已经存在了 ,那就重命名一个文件名称
String rename = System.currentTimeMillis() + "_" + filename;
if(saveFile.exists()){
filename=rename;
saveFile=new File(ROOT_PATH+ File.separator +rename); //重命名后的文件
}
//存储文件到本地磁盘
file.transferTo(saveFile);
//需要返回给前端的下载路径
String url ="http://"+ip+":"+port+"/file/download/"+ filename;
return new Result("上传成功",true,url);
}
@GetMapping ("/download/{filename}")
public Result download(@PathVariable String filename, HttpServletResponse response) throws IOException {
ServletOutputStream outputStream = response.getOutputStream();
String localFilename = ROOT_PATH+File.separator+filename; // 要获取的文件的本地路径
File localFile = new File(localFilename); //创建文件
InputStream inputStream = Files.newInputStream(localFile.toPath()); // 使用java.nio的工具类创建输入流
long fileSize =localFile.length();
byte[] buffer = new byte[(int) fileSize];
int read = inputStream.read(buffer);
outputStream.write(buffer); //是一个字节数组,也就是文件的字节流数组
return new Result(true);
}
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
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
# 1.2 细节
可以在Properties配置文件里加入
ip=localhost
来动态配置ip
# 1.3 问题
# 1.3.1 [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representati
因为返回的result对象没有get和set方法,所以jackson无法正常返回
# 1.3.2 the request was rejected because its size (112505738) exceeds the configured maximum (10485760)
上传的文件比较大,MultipartFile是spring封装的处理文件的类
,需要单独在Springboot的配置文件里单独配置可以上传的最大文件大小
#文件上传开关
spring.servlet.multipart.enabled=true
#单个文件限制
spring.servlet.multipart.max-file-size=1300MB
#请求总文件大小限制
spring.servlet.multipart.max-request-size=1300MB
#阈值,超过后文件将被写入磁盘
spring.servlet.multipart.file-size-threshold=2KB
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8