老师我的代码看起来没有问题啊
@ApiOperation("后台上传商品图片")
@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.randomUUID();//生成文件名UUID
String newFileName = uuid.toString() + suffixName;
File fileDirectory = new File(ProductConstant.FILE_UPLOAD_DIR);//创建文件夹
File destFile = new File(ProductConstant.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.getRequestURI() + "")) + "/category-product/images/" + newFileName);
} catch (URISyntaxException e) {
return ApiRestResponse.error(ImoocMallExceptionEnum.UPLOAD_FAILED);
}
}
private URI getHost(URI uri) {
URI effectiveURI;
try {
effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), ip, port, null, null, null);
} catch (URISyntaxException e) {
effectiveURI = null;
e.printStackTrace();
}
return effectiveURI;
}
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星