这里写自定义目录标题
Springboot 文件图片上传及资源映射
使用WebMvcConfigurer进行图片资源映射
private String uploadFilePath ="D://upload/";
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry..addPathPatterns("/**").excludePathPatterns("/login").excludePathPatterns("/upload/**")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**","/doc.html","/error");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(“/upload/**”).addResourceLocations(“file:”+uploadFilePath);
}
请求地址为
http://localhost:8082///wx/v1.0//upload//2022//08//26//397add5e-b68a-4bf8-b771-5b717def21aa.png
接口
@PostMapping(“/uploadPic”)
public BsResult uploadPic(@RequestParam(“file”) MultipartFile uploadFile, HttpServletRequest request) {
String fileUrl = “”;//存储生成的访问路径
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy/MM/dd/”);
String oldName = uploadFile.getOriginalFilename();
String end = oldName.substring(oldName.lastIndexOf("."));
//根据上传的文件日期,进行分类保存
String format = sdf.format(new Date()).replace("/", File.separator);
File folder = new File(uploadFilePath + File.separator + format);
if (!folder.isDirectory()) {
folder.mkdirs();
}
String newName = UUID.randomUUID().toString() + end;
try {
//保存文件
uploadFile.transferTo(new File(folder, newName));
//生成上传文件的访问路径
String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + File.separator +request.getContextPath()+ File.separator +"upload"+File.separator+ format + newName;
fileUrl = fileUrl + filePath + ",";
} catch (IOException e) {
return BsResult.error(500, e.getMessage());
}
fileUrl = fileUrl.substring(0, fileUrl.length() - 1);
return BsResult.success("上传成功!").put("fileUrl", fileUrl);
}