1、application.yml 配置
spring:
mvc:
# url访问文件路径
static-path-pattern:
2、controller
@ApiOperation(value = "文件上传接口")
@PostMapping(value = "/uploadFile")
public String generalUploadFile(@ApiParam(value = "上传的文件", required = true) @RequestPart MultipartFile file) {
return goodsService.generalUploadFile(file);
}
3、impl
@Value("${uploadDir}")
private String uploadDir;
@Override
public String generalUploadFile(MultipartFile file) {
if (Objects.isNull(file) || file.isEmpty() || file.getOriginalFilename() == null) {
log.error("文件为空");
throw new ServiceException("文件为空,请重新上传");
}
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
fileName = System.currentTimeMillis() + suffixName;
String contextPath = servletConfig.getContextPath();
String url = contextPath + uploadDir + fileName;
File newFile = new File(uploadDir + fileName);
try {
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
file.transferTo(newFile);
} catch (IOException e) {
log.error("文件写入磁盘IO异常 ", e);
throw new ServiceException("文件写入磁盘IO异常");
}
return url;
}
4、swagger 测试

5、浏览器显示
