1.直接上全部代码
@ApiOperation(value = "用户头像修改",notes = "用户头像修改",httpMethod = "POST") @PostMapping("uploadFace") public IMOOCJSONResult uploadFace( @ApiParam(name = "userId",value = "用户id",required = true) @RequestParam String userId, @ApiParam(name = "file",value = "用户头像",required = true) MultipartFile file, //文件上传 HttpServletRequest request, HttpServletResponse response){ //1.定义头像保存地址 String fileSpace=fileUpload.getImageUserFaceLocation();; //2.在路径上为每一个用户增加一个userId,用户区分不同用户上传 String uploadPathPrefix = File.separator + userId; //3.开始上传文件 if (file!=null){ FileOutputStream fileOutputStream=null; try { //4.获取文件上传的文件名称 String fileName=file.getOriginalFilename(); if (StringUtils.isNotBlank(fileName)){ //5.文件重命名 String fileNameArr[] =fileName.split("\."); //6.获取文件的后缀名 String suffix=fileNameArr[fileNameArr.length-1];
//文件格式验证 if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg") ) { return IMOOCJSONResult.errorMsg("图片格式不正确!"); } //7.文件名称重组 覆盖式上传增量式 额外拼接当前时间 String newFileName="face"+userId+"."+suffix; //8.上传的头像最终保存的位置 String finalFacePath=fileSpace+uploadPathPrefix + File.separator + newFileName; //9.用于提供给web服务器访问的地址 uploadPathPrefix+=("/"+newFileName); File outFile=new File(finalFacePath); if (outFile.getParentFile()!=null){ //10.创建文件夹 outFile.getParentFile().mkdir(); } //11.文件输出保存到目录 fileOutputStream=new FileOutputStream(outFile); InputStream inputStream=file.getInputStream(); IOUtils.copy(inputStream,fileOutputStream); } }catch (IOException e){ e.printStackTrace(); }finally { try { if (fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }else { return IMOOCJSONResult.errorMsg("文件不能为空!"); } //12.获取图片服务地址 String imageServerUrl = fileUpload.getImageServerUrl(); // 13.由于浏览器可能存在缓存的情况,所以在这里,我们需要加上时间戳来保证更新后的图片可以及时刷新 String finalUserFaceUrl = imageServerUrl + uploadPathPrefix + "?t=" + DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN); //14.更新用户头像到数据库 Users userResult=centerUserService.updateUserFace(userId,finalUserFaceUrl); userResult=setNullProperty(userResult); CookieUtils.setCookie(request,response,"user", JsonUtils.objectToJson(userResult), true); return IMOOCJSONResult.ok(); }
2.指定存储位置配置 在resources 目录下创建 file-upload-dev.properties
file.imageUserFaceLocation=D:/workspaces/images/foodie/faces file.imageServerUrl=http://localhost:8088/foodie/faces //指定图片位置(此处不全,但在代码中是补上的)
3.静态资源网络映射(不然服务是访问不到的)
@Configuration public class WebMvcConfig implements WebMvcConfigurer { // 实现静态资源的映射 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/META-INF/resources/") // 映射swagger2 .addResourceLocations("file:D:/workspaces/images/"); // 映射本地静态资源
//http://localhost:8088/foodie/faces1908017YR51G1XWH/face1908017YR51G1XWH.jpg?t=20201211154555
//完整地址http://localhost:8088/foodie/faces1908017YR51G1XWH
} @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
4.图片大小限制
servlet: multipart: max-file-size: 512000 # 文件上传大小限制为500kb max-request-size: 512000 # 请求大小限制为500kb
5.当图片大小超过设定值后,需要自定义捕获异常返回
@RestControllerAdvice public class CustomExceptionHandler { // 上传文件超过500k,捕获异常:MaxUploadSizeExceededException @ExceptionHandler(MaxUploadSizeExceededException.class) public IMOOCJSONResult handlerMaxUpload(MaxUploadSizeExceededException ex){ return IMOOCJSONResult.errorMsg("文件上传大小不能超过500k,请压缩图片或者降低图片质量再上传!"); } }