1.问题描述:
在springboot中编写了上传文件的接口:
@PostMapping("/admin/upload/file")
public ApiRestResponse upload(HttpServletRequest httpServletRequest,
@RequestParam("file") MultipartFile file){
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//生成文件名称UUID
UUID uuid = UUID.randomUUID();
String newFileName = uuid.toString() + suffixName;
//创建文件
File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
if(!fileDirectory.exists()){
if(!fileDirectory.mkdir()){
throw new ImoocMallException(ImoocMallExceptionEnum.MKDIR_FAILED);
}
}
try {
file.transferTo(destFile);
} catch (IOException e) {
e.printStackTrace();
}
try {
return ApiRestResponse.success(getHost(new URI(httpServletRequest.getRequestURL() + ""))
+ "/images/" + newFileName);
} catch (URISyntaxException e) {
return ApiRestResponse.error(ImoocMallExceptionEnum.UPLOAD_FAILED);
}
}
在PostMan中进行测试可以正常上传:
将图片的url复制到浏览器中,却不能够在浏览器页面正常回显,如下图:
2.原因:
没有配置静态资源到本地目录的映射。
3.解决方法:
在SpringBootWebMvcConfig中,对其进行静态资源到本地目录的映射配置:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:" +
Constant.FILE_UPLOAD_DIR);
}
注意:file后面不能有空格!!!本人就是这里多敲了空格,迟迟显示不了,还不容易排查!