Controller

  1. @ApiOperation(value = "用户头像修改", notes = "用户头像修改", httpMethod = "POST")
  2. @PostMapping("uploadFace")
  3. public MyJSONResult uploadFace(
  4. @ApiParam(name = "userId", value = "用户id", required = true)
  5. @RequestParam String userId,
  6. @ApiParam(name = "file", value = "用户头像", required = true)
  7. MultipartFile file,
  8. HttpServletRequest request,
  9. HttpServletResponse response) {
  10. // 定义头像保存的地址
  11. // D:\\Environment\\apache-tomcat-9.0.46\\webapps\\images\\foodie\\faces
  12. String fileSpace = fileUpload.getImageUserFaceLocation();
  13. // 在路径上为每一个用户增加一个userid,用于区分不同用户上传
  14. String uploadPathPrefix = File.separator + userId;
  15. //开上上传文件
  16. if (file != null) {
  17. FileOutputStream fileOutputStream = null;
  18. try {
  19. //获得文件上传的文件名称
  20. String fileName = file.getOriginalFilename();
  21. if (StringUtils.isNotBlank(fileName)) {
  22. //文件重命名 xxxx-face.png -> ["xxxx-face","png"]
  23. String[] fileNameArr = fileName.split("\\.");
  24. //获取文件后缀名
  25. String suffix = fileNameArr[fileNameArr.length - 1];
  26. //🔥🔥🔥图片格式限制!!!!!!防止上传恶意文件🔥🔥🔥
  27. if (!suffix.equalsIgnoreCase("png") &&
  28. !suffix.equalsIgnoreCase("jpg") &&
  29. !suffix.equalsIgnoreCase("jpeg")){
  30. return MyJSONResult.errorMap("图片格式不正确");
  31. }
  32. //文件名重组 face-{userid}.png
  33. //覆盖式上传,如使用增量式需要拼接时间
  34. String newFileName = "face-" + userId + "." + suffix;
  35. //上传的头像最终保存的位置
  36. String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;
  37. //用于提供给web服务访问的地址
  38. uploadPathPrefix += ("/" + newFileName);
  39. File outFile = new File(finalFacePath);
  40. //如果父文件夹不为空
  41. if (outFile.getParentFile() != null) {
  42. //创建文件夹
  43. outFile.getParentFile().mkdirs();
  44. }
  45. //文件输出保存到目录
  46. fileOutputStream = new FileOutputStream(outFile);
  47. InputStream inputStream = file.getInputStream();
  48. IOUtils.copy(inputStream, fileOutputStream);
  49. }
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. } finally {
  53. try {
  54. if (fileOutputStream != null) {
  55. fileOutputStream.flush();
  56. fileOutputStream.close();
  57. }
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. } else {
  63. return MyJSONResult.errorMap("文件不能为空!");
  64. }
  65. //获得图片服务地址 http://localhost:8088/foodie/faces
  66. String imageServerUrl = fileUpload.getImageServerUrl();
  67. // 由于浏览器可能存在缓存的情况,所以在这里我们需要加上时间戳,保证更新后的图片可以及时刷新
  68. String finalUserFaceUrl = imageServerUrl + uploadPathPrefix
  69. + "?t=" + DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);
  70. //更新用户头像到数据库
  71. Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);
  72. userResult = setNullProperty(userResult);
  73. CookieUtils.setCookie(request, response, "user",
  74. JsonUtils.objectToJson(userResult), true);
  75. //TODO 后续要改,增加令牌token,会整合进redis,分布式会话
  76. return MyJSONResult.ok();
  77. }

文件大小限制

在application.yml中的spring下添加配置

  1. spring:
  2. servlet:
  3. multipart:
  4. max-file-size: 512000 # 文件上传大小限制为500kb
  5. max-request-size: 512000 # 请求大小限制为500kb

image.png

捕获文件大小异常

  1. package com.shiers.exception;
  2. import com.shiers.utils.MyJSONResult;
  3. import org.springframework.web.bind.annotation.ExceptionHandler;
  4. import org.springframework.web.bind.annotation.RestControllerAdvice;
  5. import org.springframework.web.multipart.MaxUploadSizeExceededException;
  6. /**
  7. * Demo class
  8. *
  9. * @author shierS
  10. * @date 2021/6/7
  11. */
  12. //@RestControllerAdvice是Controller的增强 定义全局异常处理类 常用于全局异常的捕获处理 和请求参数的增强
  13. @RestControllerAdvice
  14. public class CustomExceptionHandler {
  15. //@ExceptionHandler(Exception.class)声明异常处理方法
  16. //上传文件超过500k,捕获异常:MaxUploadSizeExceededException
  17. @ExceptionHandler(MaxUploadSizeExceededException.class)
  18. public MyJSONResult handlerMaxUploadFile(MaxUploadSizeExceededException exception){
  19. System.out.println("=========捕获成功");
  20. return MyJSONResult.errorMsg("🤪文件上传大小不能超过500k,请压缩图片或者降低图片质量再上传!");
  21. }
  22. }

最终效果

image.png
image.png
image.png