0


若依前后端分离集成阿里云OSS分布式文件存储

在ruoyi-common的pom中添加OSS依赖

       <!-- 阿里云OSS -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>

在ruoyi-admin的application.yml文件中添加OSS配置

aliyunoss:
  # 地域节点
  endpoint: oss-cn-beijing.aliyuncs.com
  # AccessKey
  accessKeyId: shutuzijideAccessKey
  # AccessKey 秘钥
  accessKeySecret: shutuzijidemiyao
  # bucket名称
  bucketName: qumingzhennan
  # bucket下文件夹的路径
  filehost: img
  # 访问域名
  url: https://qumingzhennan.oss-cn-beijing.aliyuncs.com

在ruoyi-common的utils中添加oss目录,添加AliyunOssUploadUtils工具类

@Component
public class AliyunOssUploadUtils {
​
    private static AliyunOssConfig aliyunOssConfig;
​
​
    /**
     * 使用构造方法注入配置信息
     */
    @Autowired
    public AliyunOssUploadUtils(AliyunOssConfig aliyunOssConfig) {
        AliyunOssUploadUtils.aliyunOssConfig = aliyunOssConfig;
    }
​
    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file) throws Exception {
​
        // 生成 OSSClient
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        // 原始文件名称
        // String originalFilename = file.getOriginalFilename();
​
        // 编码文件名
        String filePathName = FileUploadUtils.extractFilename(file);
        // 文件路径名称
        filePathName = aliyunOssConfig.getFilehost() + "/" + filePathName;
        try {
            ossClient.putObject(aliyunOssConfig.getBucketName(), filePathName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return aliyunOssConfig.getUrl() + "/" + filePathName;
    }
}

在ruoyi-common的config中添加AliyunOssConfig文件

@Component
@ConfigurationProperties(prefix = "aliyunoss")
public class AliyunOssConfig {
    /**
     * 地域节点
     */
    private String endpoint;
​
    /**
     * AccessKey
     */
    private String accessKeyId;
​
    /**
     * AccessKey秘钥
     */
    private String accessKeySecret;
​
    /**
     * bucket名称
     */
    private String bucketName;
​
    /**
     * bucket下文件夹的路径
     */
    private String filehost;
​
    /**
     * 访问域名
     */
    private String url;
​
    public String getEndpoint() {
        return endpoint;
    }
​
    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }
​
    public String getAccessKeyId() {
        return accessKeyId;
    }
​
    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }
​
    public String getAccessKeySecret() {
        return accessKeySecret;
    }
​
    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }
​
    public String getBucketName() {
        return bucketName;
    }
​
    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }
​
    public String getFilehost() {
        return filehost;
    }
​
    public void setFilehost(String filehost) {
        this.filehost = filehost;
    }
​
    public String getUrl() {
        return url;
    }
​
    public void setUrl(String url) {
        this.url = url;
    }
​
    @Override
    public String toString() {
        return "AliyunOssConfig{" +
                "endpoint='" + endpoint + '\'' +
                ", accessKeyId='" + accessKeyId + '\'' +
                ", accessKeySecret='" + accessKeySecret + '\'' +
                ", bucketName='" + bucketName + '\'' +
                ", filehost='" + filehost + '\'' +
                ", url='" + url + '\'' +
                '}';
    }
}

在ruoyi-admin的controller/common的CommonController文件中,添加uploadFileOSS方法

@CrossOrigin
    @PostMapping("/uploadOSS")
    public AjaxResult uploadFileOSS(MultipartFile file) throws Exception {
        System.out.println(file);
        try {
            String url = AliyunOssUploadUtils.uploadFile(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", FileUtils.getName(url));
            ajax.put("newFileName", FileUtils.getName(url));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
​
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

在前端components/ImageUpload文件下修改index.vue

//将
    uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload"
//改为
    uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/uploadOSS", // 上传的图片服务器地址
//将handler方法中
    item = { name: this.baseUrl + item, url: this.baseUrl + item }
//改为
    item = { name: item, url: item }

至此普通的图片上传已经完成


下面是将头像修改为阿里云OSS上传 在ruoyi-admin的controller/system目录下修改SysProfileController,将原本的avatar方法修改为

 /**
     * 头像上传
     */
    @CrossOrigin
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
​
//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            String url = AliyunOssUploadUtils.uploadFile(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", FileUtils.getName(url));
            ajax.put("newFileName", FileUtils.getName(url));
            ajax.put("originalFilename", file.getOriginalFilename());
            if (userService.updateUserAvatar(loginUser.getUsername(), url))
            {
​
                ajax.put("imgUrl", url);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(url);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常,请联系管理员");
    }

修改前端views/system/user/profile下的userAvatar.vue文件中uploadImg方法,修改为

// 上传图片
  uploadImg() {
    this.$refs.cropper.getCropBlob(data => {
      let formData = new FormData();
      formData.append("avatarfile", data);
      uploadAvatar(formData).then(response => {
        this.open = false;
        // 这里之前是获取 .env中后端的请求地址 + response.imgUrl,现在要改为 response.imgUrl
        this.options.img = response.imgUrl;
        store.commit('SET_AVATAR', this.options.img);
        this.$modal.msgSuccess("修改成功");
        this.visible = false;
      });
    });
  },

在前端修改获取用户头像信息路径于store/modules目录中修改user.js文件

//将
const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
//改为
const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/profile.jpg") :  user.avatar;

登录阿里云OSS官网,在权限管理下的跨域设置中设置跨域如图

在前端views/system/user/profile下的userAvatar.vue中修改editCropper方法并添加setAvatarBase64、transBase64FromImage方法

// 编辑头像
    editCropper() {
      this.open = true;
      let _this = this;
      // 设置头像base64
      // 其中this.avatar为当前头像
      this.setAvatarBase64(store.getters.avatar, base64 => {
        _this.options.img = base64;
      });
    },
// 设置头像base64
    setAvatarBase64(src, callback) {
      let _this = this;
      let image = new Image();
      // 处理缓存
      image.src = src + "?v=" + Math.random();
      // 支持跨域图片
      image.crossOrigin = "*";
      image.onload = function() {
        let base64 = _this.transBase64FromImage(image);
        callback && callback(base64);
      };
    },
// 将网络图片转换成base64格式
    transBase64FromImage(image) {
      let canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      let ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, image.width, image.height);
      // 可选其他值 image/jpeg
      return canvas.toDataURL("image/png");
    }

至此修改完成

标签: 阿里云 java vue

本文转载自: https://blog.csdn.net/qq_57943924/article/details/129215834
版权归原作者 六六不靠谱 所有, 如有侵权,请联系我们删除。

“若依前后端分离集成阿里云OSS分布式文件存储”的评论:

还没有评论