1. import org.springframework.web.multipart.MultipartFile;
    2. public MyJSONResult uploadFace(MultipartFile file) {
    3. // 定义文件保存的地址
    4. String fileSpace = fileUpload.getImageUserFaceLocation();
    5. //开上上传文件
    6. if (file != null) {
    7. FileOutputStream fileOutputStream = null;
    8. try {
    9. //获得文件上传的文件名称
    10. String fileName = file.getOriginalFilename();
    11. if (StringUtils.isNotBlank(fileName)) {
    12. //文件重命名 xxxx-face.png -> ["xxxx-face","png"]
    13. String[] fileNameArr = fileName.split("\\.");
    14. //获取文件后缀名
    15. String suffix = fileNameArr[fileNameArr.length - 1];
    16. //文件名重组 face-{userid}.png
    17. //覆盖式上传,如使用增量式需要拼接时间
    18. String newFileName = "face-" + userId + "." + suffix;
    19. //上传文件最终保存的位置
    20. String finalFacePath = fileSpace + File.separator + newFileName;
    21. File outFile = new File(finalFacePath);
    22. //如果父文件夹不为空
    23. if (outFile.getParentFile() != null) {
    24. //创建文件夹
    25. outFile.getParentFile().mkdirs();
    26. }
    27. //文件输出保存到目录
    28. fileOutputStream = new FileOutputStream(outFile);
    29. InputStream inputStream = file.getInputStream();
    30. IOUtils.copy(inputStream, fileOutputStream);
    31. }
    32. } catch (IOException e) {
    33. e.printStackTrace();
    34. } finally {
    35. try {
    36. if (fileOutputStream != null) {
    37. fileOutputStream.flush();
    38. fileOutputStream.close();
    39. }
    40. } catch (IOException e) {
    41. e.printStackTrace();
    42. }
    43. }
    44. } else {
    45. return MyJSONResult.errorMap("文件不能为空!");
    46. }
    47. return MyJSONResult.ok();
    48. }