SpringBoot用戶頭像上傳


1、上傳到本地服務器

controller層主要以MultipartFile接收即可,這里返回給前端的該文件保存后的相對路徑

    @RequestMapping(value = "/application/file/upload", method = RequestMethod.POST)
    public Object uoloadFile(@RequestParam("file") MultipartFile file) {
        return buildMessage(ResultModel.SUCCESS, appService.uoloadFile(file));
    }

2.下面看下service層upload的具體實現:

    public String uploadFile(MultipartFile file) throws NotifyException {
        // 首先校驗圖片格式
        List<String> imageType = Lists.newArrayList("jpg","jpeg", "png", "bmp", "gif");
        // 獲取文件名,帶后綴
        String originalFilename = file.getOriginalFilename();
        // 獲取文件的后綴格式
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (imageType.contains(fileSuffix)) {
            // 只有當滿足圖片格式時才進來,重新賦圖片名,防止出現名稱重復的情況
            String newFileName = UUIDTypeHandler.createUUID() + originalFilename;
            // 該方法返回的為當前項目的工作目錄,即在哪個地方啟動的java線程
            String dirPath = System.getProperty("user.dir");
            String path = File.separator + "uploadImg" + File.separator + newFileName;
            File destFile = new File(dirPath + path);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(destFile);
                // 將相對路徑返回給前端
                return path;
            } catch (IOException e) {
                log.error("upload pic error");
                return null;
            }
        } else {
            // 非法文件
            log.error("the picture's suffix is illegal");
            throw new NotifyException(ExceptionConstants.FILE_UPLOAD_ERROR);
        }
    }

上述代碼是以上傳圖片為例,上傳文件同理,只要去掉圖片格式驗證即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM