Controller
@ApiOperation(value = "用户头像修改", notes = "用户头像修改", httpMethod = "POST")
@PostMapping("uploadFace")
public MyJSONResult uploadFace(
@ApiParam(name = "userId", value = "用户id", required = true)
@RequestParam String userId,
@ApiParam(name = "file", value = "用户头像", required = true)
MultipartFile file,
HttpServletRequest request,
HttpServletResponse response) {
// 定义头像保存的地址
// D:\\Environment\\apache-tomcat-9.0.46\\webapps\\images\\foodie\\faces
String fileSpace = fileUpload.getImageUserFaceLocation();
// 在路径上为每一个用户增加一个userid,用于区分不同用户上传
String uploadPathPrefix = File.separator + userId;
//开上上传文件
if (file != null) {
FileOutputStream fileOutputStream = null;
try {
//获得文件上传的文件名称
String fileName = file.getOriginalFilename();
if (StringUtils.isNotBlank(fileName)) {
//文件重命名 xxxx-face.png -> ["xxxx-face","png"]
String[] fileNameArr = fileName.split("\\.");
//获取文件后缀名
String suffix = fileNameArr[fileNameArr.length - 1];
//🔥🔥🔥图片格式限制!!!!!!防止上传恶意文件🔥🔥🔥
if (!suffix.equalsIgnoreCase("png") &&
!suffix.equalsIgnoreCase("jpg") &&
!suffix.equalsIgnoreCase("jpeg")){
return MyJSONResult.errorMap("图片格式不正确");
}
//文件名重组 face-{userid}.png
//覆盖式上传,如使用增量式需要拼接时间
String newFileName = "face-" + userId + "." + suffix;
//上传的头像最终保存的位置
String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;
//用于提供给web服务访问的地址
uploadPathPrefix += ("/" + newFileName);
File outFile = new File(finalFacePath);
//如果父文件夹不为空
if (outFile.getParentFile() != null) {
//创建文件夹
outFile.getParentFile().mkdirs();
}
//文件输出保存到目录
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 MyJSONResult.errorMap("文件不能为空!");
}
//获得图片服务地址 http://localhost:8088/foodie/faces
String imageServerUrl = fileUpload.getImageServerUrl();
// 由于浏览器可能存在缓存的情况,所以在这里我们需要加上时间戳,保证更新后的图片可以及时刷新
String finalUserFaceUrl = imageServerUrl + uploadPathPrefix
+ "?t=" + DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);
//更新用户头像到数据库
Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);
userResult = setNullProperty(userResult);
CookieUtils.setCookie(request, response, "user",
JsonUtils.objectToJson(userResult), true);
//TODO 后续要改,增加令牌token,会整合进redis,分布式会话
return MyJSONResult.ok();
}
文件大小限制
在application.yml中的spring下添加配置
spring:
servlet:
multipart:
max-file-size: 512000 # 文件上传大小限制为500kb
max-request-size: 512000 # 请求大小限制为500kb
捕获文件大小异常
package com.shiers.exception;
import com.shiers.utils.MyJSONResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
/**
* Demo class
*
* @author shierS
* @date 2021/6/7
*/
//@RestControllerAdvice是Controller的增强 定义全局异常处理类 常用于全局异常的捕获处理 和请求参数的增强
@RestControllerAdvice
public class CustomExceptionHandler {
//@ExceptionHandler(Exception.class)声明异常处理方法
//上传文件超过500k,捕获异常:MaxUploadSizeExceededException
@ExceptionHandler(MaxUploadSizeExceededException.class)
public MyJSONResult handlerMaxUploadFile(MaxUploadSizeExceededException exception){
System.out.println("=========捕获成功");
return MyJSONResult.errorMsg("🤪文件上传大小不能超过500k,请压缩图片或者降低图片质量再上传!");
}
}