1.在application.yml配置springboot的静态资源的访问路径:
spring:
# 配置静态资源路径
web:
resources:
static-locations: file:${project.upload-url}
servlet:
multipart:
max-request-size: 50MB
max-file-size: 50MB
project:
upload-url: D:/uploadFile/
2.上传代码:
public ApiResult upload(@RequestParam MultipartFile file,ServletRequest request) {
try {
if (file.isEmpty()) {
return ApiResult.fail("请选择要上传的文件");
}
System.out.println(file);
byte[] bytes = file.getBytes();
String dateString = DateFormatUtils.format(new Date(), "yyyy-MM-dd-hh-mm-ss");
String filePath = dateString + "_" + file.getOriginalFilename();
Path path = Paths.get(project.getUploadUrl() + filePath);
Files.write(path, bytes);
Map map = new HashMap<String, String>();
String allFilePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort()+"/"+filePath;
map.put("path", project.getUploadUrl());
map.put("allPath", project.getUploadUrl() + filePath);
map.put("filePath", filePath);
map.put("allFilePath", allFilePath);
return ApiResult.success(map);
} catch (Exception e) {
e.printStackTrace();
return ApiResult.fail("上传失败");
}
}
allFilePath就是可以本地访问的http路径,文件被保存到D:/uploadFile/中。
版权声明:本文为weixin_42471170原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。