配置限制文件上传大小
servlet:
multipart:
max-file-size: 5MB # 限制文件上传的大小
SpringMVC会封装为一个接口:MultipartFile
@Controller @RequestMapping("upload") public class UploadController { @Autowired private UploadService uploadService; /** * 图片上传 * @param file * @return */ @PostMapping("image") public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file){ String url = this.uploadService.upload(file); if (StringUtils.isBlank(url)) { return ResponseEntity.badRequest().build(); } return ResponseEntity.status(HttpStatus.CREATED).body(url); } }
对上传的内容进行校验:
-
校验文件大小
-
校验文件的媒体类型
-
校验文件的内容
@Service public class UploadService { private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif"); private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class); public String upload(MultipartFile file) { String originalFilename = file.getOriginalFilename(); // 校验文件的类型 String contentType = file.getContentType(); if (!CONTENT_TYPES.contains(contentType)){ // 文件类型不合法,直接返回null LOGGER.info("文件类型不合法:{}", originalFilename); return null; } try { // 校验文件的内容 BufferedImage bufferedImage = ImageIO.read(file.getInputStream()); if (bufferedImage == null){ LOGGER.info("文件内容不合法:{}", originalFilename); return null; } // 保存到服务器 file.transferTo(new File("C:\test\images\" + originalFilename)); // 生成url地址,返回 return "http://image.test.com/" + originalFilename; } catch (IOException e) { LOGGER.info("服务器内部错误:{}", originalFilename); e.printStackTrace(); } return null; } }