1.目录结构 如图: 2.后端代码: @RequestMapping("upload") @RestController public class UploadController { @Autowired private UploadService uploadService; /** * 上传图片 */ @PostMapping("image") public BaseResult uploadImage(@RequestParam("file") MultipartFile file) throws LyException { return ResultUtil.success(uploadService.uploadImage(file)) ; } }
@Service @Slf4j public class UploadService { private static final List<String> ALLOW_TYPE = Arrays.asList("image/jpg","image/png","image/bmp"); public String uploadImage(MultipartFile file) throws LyException { String fileName = file.getOriginalFilename(); fileName = UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf(".")); File dest = new File("F:\\upload" ,fileName); try { //校验文件类型 String contentType = file.getContentType(); if(ALLOW_TYPE.contains(contentType)){ throw new LyException(ExceptionEnum.IMAGE_TYPE_ERROR); } //校验文件内容 BufferedImage read = ImageIO.read(file.getInputStream()); if(read == null){ throw new LyException(ExceptionEnum.PRICE_CANNOT_BE_NULL.IMAGE_TYPE_ERROR); } file.transferTo(dest); return "http://localhost:8080/queryIma/"+fileName; //啰嗦一句 ,如果是springcloud 集群 应该返回集群路径 //如:return "http://api.taobao.com/api/upload/queryIma/"+fileName; } catch (IOException e) { //记录日志 log.error("上传文件失败",e ); throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR); } } }
@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler( "/queryIma/**") .addResourceLocations("file:"+ "F:/upload/"); //本地保存路径 //registry.addResourceHandler( "/upload/queryIma/**") .addResourceLocations("file:"+ "F:/upload/"); //对应上面集群路径,去掉/api } }
这篇文章 更好:https://www.cnblogs.com/hhhshct/p/9121158.html