springboot项目修改个人头像

喜欢ヅ旅行 2022-09-09 02:10 403阅读 0赞

#

    • 1.配置类
    • 2.文件上传工具类
    • 3.前端页面
    • 4.控制层:

1.配置类

  1. # 项目相关配置
  2. ruoyi:
  3. # 名称
  4. name: RuoYi
  5. # 版本
  6. version: 4.6.2
  7. # 版权年份
  8. copyrightYear: 2021
  9. # 实例演示开关
  10. demoEnabled: true
  11. # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)
  12. profile: C:\Users\14172\AppData\Local
  13. # 获取ip地址开关
  14. addressEnabled: false
  15. /** * 全局配置类 * * @author ruoyi */
  16. @Component
  17. @ConfigurationProperties(prefix = "ruoyi")
  18. public class RuoYiConfig
  19. {
  20. /** 项目名称 */
  21. private static String name;
  22. /** 版本 */
  23. private static String version;
  24. /** 版权年份 */
  25. private static String copyrightYear;
  26. /** 实例演示开关 */
  27. private static boolean demoEnabled;
  28. /** 上传路径 */
  29. private static String profile;
  30. /** 获取地址开关 */
  31. private static boolean addressEnabled;
  32. public static String getName()
  33. {
  34. return name;
  35. }
  36. public void setName(String name)
  37. {
  38. RuoYiConfig.name = name;
  39. }
  40. public static String getVersion()
  41. {
  42. return version;
  43. }
  44. public void setVersion(String version)
  45. {
  46. RuoYiConfig.version = version;
  47. }
  48. public static String getCopyrightYear()
  49. {
  50. return copyrightYear;
  51. }
  52. public void setCopyrightYear(String copyrightYear)
  53. {
  54. RuoYiConfig.copyrightYear = copyrightYear;
  55. }
  56. public static boolean isDemoEnabled()
  57. {
  58. return demoEnabled;
  59. }
  60. public void setDemoEnabled(boolean demoEnabled)
  61. {
  62. RuoYiConfig.demoEnabled = demoEnabled;
  63. }
  64. public static String getProfile()
  65. {
  66. return profile;
  67. }
  68. public void setProfile(String profile)
  69. {
  70. RuoYiConfig.profile = profile;
  71. }
  72. public static boolean isAddressEnabled()
  73. {
  74. return addressEnabled;
  75. }
  76. public void setAddressEnabled(boolean addressEnabled)
  77. {
  78. RuoYiConfig.addressEnabled = addressEnabled;
  79. }
  80. /** * 获取导入上传路径 */
  81. public static String getImportPath()
  82. {
  83. return getProfile() + "/import";
  84. }
  85. /** * 获取头像上传路径 */
  86. public static String getAvatarPath()
  87. {
  88. return getProfile() + "/avatar";
  89. }
  90. /** * 获取下载路径 */
  91. public static String getDownloadPath()
  92. {
  93. return getProfile() + "/download/";
  94. }
  95. /** * 获取上传路径 */
  96. public static String getUploadPath()
  97. {
  98. return getProfile() + "/upload";
  99. }
  100. }

2.文件上传工具类

  1. /** * 文件上传工具类 * * @author ruoyi */
  2. public class FileUploadUtils
  3. {
  4. /** * 默认大小 50M */
  5. public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
  6. /** * 默认的文件名最大长度 100 */
  7. public static final int DEFAULT_FILE_NAME_LENGTH = 100;
  8. /** * 默认上传的地址 */
  9. private static String defaultBaseDir = RuoYiConfig.getProfile();
  10. public static void setDefaultBaseDir(String defaultBaseDir)
  11. {
  12. FileUploadUtils.defaultBaseDir = defaultBaseDir;
  13. }
  14. public static String getDefaultBaseDir()
  15. {
  16. return defaultBaseDir;
  17. }
  18. /** * 以默认配置进行文件上传 * * @param file 上传的文件 * @return 文件名称 * @throws Exception */
  19. public static final String upload(MultipartFile file) throws IOException
  20. {
  21. try
  22. {
  23. return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
  24. }
  25. catch (Exception e)
  26. {
  27. throw new IOException(e.getMessage(), e);
  28. }
  29. }
  30. /** * 根据文件路径上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @return 文件名称 * @throws IOException */
  31. public static final String upload(String baseDir, MultipartFile file) throws IOException
  32. {
  33. try
  34. {
  35. return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
  36. }
  37. catch (Exception e)
  38. {
  39. throw new IOException(e.getMessage(), e);
  40. }
  41. }
  42. /** * 文件上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @param allowedExtension 上传文件类型 * @return 返回上传成功的文件名 * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws FileNameLengthLimitExceededException 文件名太长 * @throws IOException 比如读写文件出错时 * @throws InvalidExtensionException 文件校验异常 */
  43. public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
  44. throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
  45. InvalidExtensionException
  46. {
  47. int fileNamelength = file.getOriginalFilename().length();
  48. if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
  49. {
  50. throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
  51. }
  52. assertAllowed(file, allowedExtension);
  53. String fileName = extractFilename(file);
  54. File desc = getAbsoluteFile(baseDir, fileName);
  55. file.transferTo(desc);
  56. String pathFileName = getPathFileName(baseDir, fileName);
  57. return pathFileName;
  58. }
  59. /** * 编码文件名 */
  60. public static final String extractFilename(MultipartFile file)
  61. {
  62. String fileName = file.getOriginalFilename();
  63. String extension = getExtension(file);
  64. fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
  65. return fileName;
  66. }
  67. public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
  68. {
  69. File desc = new File(uploadDir + File.separator + fileName);
  70. if (!desc.exists())
  71. {
  72. if (!desc.getParentFile().exists())
  73. {
  74. desc.getParentFile().mkdirs();
  75. }
  76. }
  77. return desc;
  78. }
  79. public static final String getPathFileName(String uploadDir, String fileName) throws IOException
  80. {
  81. int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
  82. String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
  83. String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
  84. return pathFileName;
  85. }
  86. /** * 文件大小校验 * * @param file 上传的文件 * @return * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws InvalidExtensionException */
  87. public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
  88. throws FileSizeLimitExceededException, InvalidExtensionException
  89. {
  90. long size = file.getSize();
  91. if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
  92. {
  93. throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
  94. }
  95. String fileName = file.getOriginalFilename();
  96. String extension = getExtension(file);
  97. if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
  98. {
  99. if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
  100. {
  101. throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
  102. fileName);
  103. }
  104. else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
  105. {
  106. throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
  107. fileName);
  108. }
  109. else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
  110. {
  111. throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
  112. fileName);
  113. }
  114. else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION)
  115. {
  116. throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
  117. fileName);
  118. }
  119. else
  120. {
  121. throw new InvalidExtensionException(allowedExtension, extension, fileName);
  122. }
  123. }
  124. }
  125. /** * 判断MIME类型是否是允许的MIME类型 * * @param extension * @param allowedExtension * @return */
  126. public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
  127. {
  128. for (String str : allowedExtension)
  129. {
  130. if (str.equalsIgnoreCase(extension))
  131. {
  132. return true;
  133. }
  134. }
  135. return false;
  136. }
  137. /** * 获取文件名的后缀 * * @param file 表单文件 * @return 后缀名 */
  138. public static final String getExtension(MultipartFile file)
  139. {
  140. String extension = FilenameUtils.getExtension(file.getOriginalFilename());
  141. if (StringUtils.isEmpty(extension))
  142. {
  143. extension = MimeTypeUtils.getExtension(file.getContentType());
  144. }
  145. return extension;
  146. }
  147. }

3.前端页面

  1. <body class="white-bg">
  2. <div class="row container">
  3. <div class="col-md-10">
  4. <div class="imageBox">
  5. <img id="avatar" th:src="(${#strings.isEmpty(user.avatar)}) ? @{/img/profile.jpg} : @{${user.avatar}}" th:onerror="'this.src=\'' + @{ '/img/profile.jpg'} + '\''">
  6. </div>
  7. <div class="action">
  8. <div class="new-contentarea tc">
  9. <a href="javascript:void(0)" class="upload-img"><label for="inputImage">上传图像</label> </a>
  10. <input type="file" name="avatar" id="inputImage" accept="image/*"/>
  11. </div>
  12. <button type="button" class="btn-custom" data-method="zoom" data-option="0.1"><i class="fa fa-search-plus"></i></button>
  13. <button type="button" class="btn-custom" data-method="zoom" data-option="-0.1"><i class="fa fa-search-minus"></i></button>
  14. <button type="button" class="btn-custom" data-method="rotate" data-option="-45"><i class="fa fa-rotate-left"></i></button>
  15. <button type="button" class="btn-custom" data-method="rotate" data-option="45"><i class="fa fa-rotate-right"></i></button>
  16. <button type="button" class="btn-custom" data-method="scaleX" data-option="-1"><i class="fa fa-arrows-h"></i></button>
  17. <button type="button" class="btn-custom" data-method="scaleY" data-option="-1"><i class="fa fa-arrows-v"></i></button>
  18. <button type="button" class="btn-custom" data-method="reset"><i class="fa fa-refresh"></i></button>
  19. </div>
  20. </div>
  21. <div class="col-md-2">
  22. <div class="cropped">
  23. <div class="preview-box">
  24. <div class="img-preview preview-xs"></div>
  25. </div>
  26. <div class="preview-box">
  27. <div class="img-preview preview-sm"></div>
  28. </div>
  29. <div class="preview-box">
  30. <div class="img-preview preview-md"></div>
  31. </div>
  32. </div>
  33. </div>
  34. </div>
  35. <script type="text/javascript"> var cropper; var croppable = false; $(window).load(function() { var image = document.getElementById('avatar'); cropper = new Cropper(image, { aspectRatio: 1, viewMode: 1, autoCropArea: 0.9, preview: '.img-preview', ready: function () { croppable = true; } }) $('#inputImage').on('change', function() { var reader = new FileReader(); var file = $('#inputImage')[0].files[0]; if (/^image\/\w+$/.test(file.type)) { reader.onload = function(e) { if(croppable){ cropper.replace(e.target.result) } } reader.readAsDataURL(this.files[0]); } else { $.modal.alertWarning('请选择一个图片文件。'); } }); $('.btn-custom').on('click',function (e) { if (!croppable) { $.modal.alertWarning("裁剪框加载中,请稍后..."); return; } var data = { method: $(this).data('method'), option: $(this).data('option') || undefined, }; var result = cropper[data.method](data.option, data.secondOption); if(['scaleX','scaleY'].indexOf(data.method) !== -1){ $(this).data('option', -data.option) } }) }); function submitHandler() { if (!croppable) { $.modal.alertWarning("裁剪框加载中,请稍后..."); return } cropper.getCroppedCanvas().toBlob(function(img) { var formdata = new FormData(); formdata.append("avatarfile", img); $.ajax({ url: ctx + "system/user/profile/updateAvatar", data: formdata, type: "post", processData: false, contentType: false, success: function(result) { $.operate.saveSuccess(result); } }) }); } $(window).resize(function() { $('.imageBox').height($(window).height() - 80); $('.cropped').height($(window).height() - 40); }).resize(); if (!HTMLCanvasElement.prototype.toBlob) { Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', { value: function(callback, type, quality) { var canvas = this; setTimeout(function() { var binStr = atob(canvas.toDataURL(type, quality).split(',')[1]); var len = binStr.length; var arr = new Uint8Array(len); for (var i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); } callback(new Blob([arr], { type: type || 'image/png' })); }); } }); } </script>
  36. </body>

4.控制层:

  1. @PostMapping("/updateAvatar")
  2. @ResponseBody
  3. public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file)
  4. {
  5. SysUser currentUser = getSysUser();
  6. try
  7. {
  8. if (!file.isEmpty())
  9. {
  10. System.out.println(RuoYiConfig.getAvatarPath());
  11. String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
  12. currentUser.setAvatar(avatar);
  13. if (userService.updateUserInfo(currentUser) > 0)
  14. {
  15. setSysUser(userService.selectUserById(currentUser.getUserId()));
  16. return success();
  17. }
  18. }
  19. return error();
  20. }
  21. catch (Exception e)
  22. {
  23. log.error("修改头像失败!", e);
  24. return error(e.getMessage());
  25. }
  26. }

效果
在这里插入图片描述
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,403人围观)

还没有评论,来说两句吧...

相关阅读

    相关 layui修改头像功能

    前言 场景大概是用户点击修改头像,会显示一个弹出框,展示当前系统所有图片,用户选择了一张之后,就会覆盖原有的那一张,注意,不能照搬,要自己调试修改的,因为每个公司重新都封

    相关 uniapp修改头像

    以下将是 uniapp 借用七牛云修改头像的代码,但是其他也可借鉴,原理相同,局部更改即可。 以下代码用到的地址皆为七牛云的地址,上传图片很方便,会给你返回图片地址,个人用