前端上传图片到OSS实现

92 阅读1分钟

背景: 用户头像信息存储在阿里云

安装并引入ali-oss

// 安装
npm install ali-oss

// 引入使用
import OSS from 'ali-oss'

创建存储对象并将图片上传

 /*创建存储对象*/
    createOss(){
      const endpoint = this.OssInfo?.endpoint
      const region = endpoint.replace('.aliyuncs.com', '')
      const bucket = this.OssInfo?.image?.bucket
      const { accessKeyId, secretAccessKey, sessionToken } = this.AliyunInfo
      let client = new OSS({
        region,
        accessKeyId: accessKeyId,
        accessKeySecret: secretAccessKey,
        bucket: bucket,
        stsToken: sessionToken,
        secure: true,
      })
      return client;
    },
    /*图片压缩上传到阿里云*/
    async compressorImage(file){
      const client = this.createOss(file)
      const cdnHost = this.OssInfo?.image?.cdnHost
      const fileName = file.name
      const suffix = fileName.substr(fileName.indexOf("."))
      const timestampStr = timestamp()
      const storeAs = 'xxx/'+timestampStr+suffix // 路径+时间戳+后缀名
      const IMAGE_SIZE = 1 * 1024 * 1024
      let compressImage = file
      
      // Compressor很多机型都不兼容
      // if(file.size > IMAGE_SIZE && this.$deviceType() === 'android'){
      //   compressImage = await Compressor(file,{quality: 0.5})
      // }

      // object表示上传到OSS的文件名称。file表示浏览器中需要上传的文件,支持HTML5 file和Blob类型。
      return new Promise( (resolve) => {
        client.put(storeAs, compressImage).then(() => {
          resolve(cdnHost+storeAs)
        }).catch(() => {
          resolve(false)
        })
      })
    }
  }, 
  
 // 在需要上传的时机调用compressorImage方法,把对应的文件作为参数传入
 // const resUrl = await this.compressorImage(file.file)

需要注意的是,在上传之前需要获取对应的 上传域和阿里云key

async getOssInfo(){
      const resOssInfo = await this.$axios({
        method: 'POST',
        url: `${this.PUB_BASE_URL}/api/xxx/xxx/xxx`,
        data: {
          request_header: this.HEADER,
          request_data: {
            version: 11
          }
        }
      })
      if(resOssInfo.code === 0){
        this.OssInfo = resOssInfo?.data?.info ? resOssInfo.data.info : {}
      }
    },
    /*获取阿里云key*/
    async getAliyunInfo(){
      const resAliyunInfo = await this.$axios({
        method: 'POST',
        url: `${this.PUB_BASE_URL}/api/api/xxx/xxx/xxx`,
        data: {
          request_header: this.HEADER,
          request_data: {
            version: 11
          }
        }
      })
      if(resAliyunInfo.code === 0){
        this.AliyunInfo = resAliyunInfo?.data?.aliyunInfo ? resAliyunInfo.data.aliyunInfo : {}
      }
    },