springboot项目修改个人头像
生活随笔
收集整理的這篇文章主要介紹了
springboot项目修改个人头像
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 1.配置類
- 2.文件上傳工具類
- 3.前端頁面
- 4.控制層:
1.配置類
# 項目相關配置 ruoyi:# 名稱name: RuoYi# 版本version: 4.6.2# 版權年份copyrightYear: 2021# 實例演示開關demoEnabled: true# 文件路徑 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)profile: C:\Users\14172\AppData\Local# 獲取ip地址開關addressEnabled: false /*** 全局配置類* * @author ruoyi*/ @Component @ConfigurationProperties(prefix = "ruoyi") public class RuoYiConfig {/** 項目名稱 */private static String name;/** 版本 */private static String version;/** 版權年份 */private static String copyrightYear;/** 實例演示開關 */private static boolean demoEnabled;/** 上傳路徑 */private static String profile;/** 獲取地址開關 */private static boolean addressEnabled;public static String getName(){return name;}public void setName(String name){RuoYiConfig.name = name;}public static String getVersion(){return version;}public void setVersion(String version){RuoYiConfig.version = version;}public static String getCopyrightYear(){return copyrightYear;}public void setCopyrightYear(String copyrightYear){RuoYiConfig.copyrightYear = copyrightYear;}public static boolean isDemoEnabled(){return demoEnabled;}public void setDemoEnabled(boolean demoEnabled){RuoYiConfig.demoEnabled = demoEnabled;}public static String getProfile(){return profile;}public void setProfile(String profile){RuoYiConfig.profile = profile;}public static boolean isAddressEnabled(){return addressEnabled;}public void setAddressEnabled(boolean addressEnabled){RuoYiConfig.addressEnabled = addressEnabled;}/*** 獲取導入上傳路徑*/public static String getImportPath(){return getProfile() + "/import";}/*** 獲取頭像上傳路徑*/public static String getAvatarPath(){return getProfile() + "/avatar";}/*** 獲取下載路徑*/public static String getDownloadPath(){return getProfile() + "/download/";}/*** 獲取上傳路徑*/public static String getUploadPath(){return getProfile() + "/upload";} }2.文件上傳工具類
/*** 文件上傳工具類* * @author ruoyi*/ public class FileUploadUtils {/*** 默認大小 50M*/public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;/*** 默認的文件名最大長度 100*/public static final int DEFAULT_FILE_NAME_LENGTH = 100;/*** 默認上傳的地址*/private static String defaultBaseDir = RuoYiConfig.getProfile();public static void setDefaultBaseDir(String defaultBaseDir){FileUploadUtils.defaultBaseDir = defaultBaseDir;}public static String getDefaultBaseDir(){return defaultBaseDir;}/*** 以默認配置進行文件上傳** @param file 上傳的文件* @return 文件名稱* @throws Exception*/public static final String upload(MultipartFile file) throws IOException{try{return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);}catch (Exception e){throw new IOException(e.getMessage(), e);}}/*** 根據文件路徑上傳** @param baseDir 相對應用的基目錄* @param file 上傳的文件* @return 文件名稱* @throws IOException*/public static final String upload(String baseDir, MultipartFile file) throws IOException{try{return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);}catch (Exception e){throw new IOException(e.getMessage(), e);}}/*** 文件上傳** @param baseDir 相對應用的基目錄* @param file 上傳的文件* @param allowedExtension 上傳文件類型* @return 返回上傳成功的文件名* @throws FileSizeLimitExceededException 如果超出最大大小* @throws FileNameLengthLimitExceededException 文件名太長* @throws IOException 比如讀寫文件出錯時* @throws InvalidExtensionException 文件校驗異常*/public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,InvalidExtensionException{int fileNamelength = file.getOriginalFilename().length();if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH){throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);}assertAllowed(file, allowedExtension);String fileName = extractFilename(file);File desc = getAbsoluteFile(baseDir, fileName);file.transferTo(desc);String pathFileName = getPathFileName(baseDir, fileName);return pathFileName;}/*** 編碼文件名*/public static final String extractFilename(MultipartFile file){String fileName = file.getOriginalFilename();String extension = getExtension(file);fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;return fileName;}public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException{File desc = new File(uploadDir + File.separator + fileName);if (!desc.exists()){if (!desc.getParentFile().exists()){desc.getParentFile().mkdirs();}}return desc;}public static final String getPathFileName(String uploadDir, String fileName) throws IOException{int dirLastIndex = RuoYiConfig.getProfile().length() + 1;String currentDir = StringUtils.substring(uploadDir, dirLastIndex);String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;return pathFileName;}/*** 文件大小校驗** @param file 上傳的文件* @return* @throws FileSizeLimitExceededException 如果超出最大大小* @throws InvalidExtensionException*/public static final void assertAllowed(MultipartFile file, String[] allowedExtension)throws FileSizeLimitExceededException, InvalidExtensionException{long size = file.getSize();if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE){throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);}String fileName = file.getOriginalFilename();String extension = getExtension(file);if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)){if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION){throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,fileName);}else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION){throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,fileName);}else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION){throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,fileName);}else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION){throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,fileName);}else{throw new InvalidExtensionException(allowedExtension, extension, fileName);}}}/*** 判斷MIME類型是否是允許的MIME類型** @param extension* @param allowedExtension* @return*/public static final boolean isAllowedExtension(String extension, String[] allowedExtension){for (String str : allowedExtension){if (str.equalsIgnoreCase(extension)){return true;}}return false;}/*** 獲取文件名的后綴* * @param file 表單文件* @return 后綴名*/public static final String getExtension(MultipartFile file){String extension = FilenameUtils.getExtension(file.getOriginalFilename());if (StringUtils.isEmpty(extension)){extension = MimeTypeUtils.getExtension(file.getContentType());}return extension;} }3.前端頁面
<body class="white-bg"><div class="row container"><div class="col-md-10"><div class="imageBox"><img id="avatar" th:src="(${#strings.isEmpty(user.avatar)}) ? @{/img/profile.jpg} : @{${user.avatar}}" th:onerror="'this.src=\'' + @{'/img/profile.jpg'} + '\''"></div><div class="action"><div class="new-contentarea tc"><a href="javascript:void(0)" class="upload-img"><label for="inputImage">上傳圖像</label> </a><input type="file" name="avatar" id="inputImage" accept="image/*"/></div><button type="button" class="btn-custom" data-method="zoom" data-option="0.1"><i class="fa fa-search-plus"></i></button><button type="button" class="btn-custom" data-method="zoom" data-option="-0.1"><i class="fa fa-search-minus"></i></button><button type="button" class="btn-custom" data-method="rotate" data-option="-45"><i class="fa fa-rotate-left"></i></button><button type="button" class="btn-custom" data-method="rotate" data-option="45"><i class="fa fa-rotate-right"></i></button><button type="button" class="btn-custom" data-method="scaleX" data-option="-1"><i class="fa fa-arrows-h"></i></button><button type="button" class="btn-custom" data-method="scaleY" data-option="-1"><i class="fa fa-arrows-v"></i></button><button type="button" class="btn-custom" data-method="reset"><i class="fa fa-refresh"></i></button></div></div><div class="col-md-2"><div class="cropped"><div class="preview-box"><div class="img-preview preview-xs"></div></div><div class="preview-box"><div class="img-preview preview-sm"></div></div><div class="preview-box"><div class="img-preview preview-md"></div></div></div></div></div> <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> </body>4.控制層:
@PostMapping("/updateAvatar")@ResponseBodypublic AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file){SysUser currentUser = getSysUser();try{if (!file.isEmpty()){System.out.println(RuoYiConfig.getAvatarPath());String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);currentUser.setAvatar(avatar);if (userService.updateUserInfo(currentUser) > 0){setSysUser(userService.selectUserById(currentUser.getUserId()));return success();}}return error();}catch (Exception e){log.error("修改頭像失敗!", e);return error(e.getMessage());}}效果
總結
以上是生活随笔為你收集整理的springboot项目修改个人头像的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows查看java进程详细信息的
- 下一篇: 用aspect在springboot中记