import org.springframework.web.multipart.MultipartFile;
public MyJSONResult uploadFace(MultipartFile file) {
// 定义文件保存的地址
String fileSpace = fileUpload.getImageUserFaceLocation();
//开上上传文件
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];
//文件名重组 face-{userid}.png
//覆盖式上传,如使用增量式需要拼接时间
String newFileName = "face-" + userId + "." + suffix;
//上传文件最终保存的位置
String finalFacePath = fileSpace + File.separator + 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("文件不能为空!");
}
return MyJSONResult.ok();
}