vue 封裝使用ali-oss上傳圖片


import { get } from "../axios/axiosType"
import OSS from "ali-oss";
import { uuid } from "vue-uuid";

/*
 * type 上傳路徑類型
 * file 上傳文件
 * progress 進度條回調
 * */
export function aliOssUpload(type, file, progress) {
  return new Promise((resolve, reject) => {
    // 成功后返回圖片信息
    let image = {
      title: file.name,
      url: "",
      width: "",
      height: "",
      pictureMd5: "",
    }
    /*
     * 創建Image獲取圖片寬高
     * */
    const URL = window.URL || Window.webkiURL
    let img = new Image()
    img.onload = function (e) {
      image.width = this.width
      image.height = this.height
    }
    img.src = URL.createObjectURL(file)
    get("/common/returnOssToken?type=" + type).then((res) => {
      if(res.code == 0) {
        let OssData = res.data
        let client = new OSS({
          region: "oss-cn-hangzhou",// 服務器所在地區
          bucket: "lq-usr-pic",// 阿里雲對應bucket名稱
          accessKeyId: OssData.accessKeyId,// oss對應令牌id
          accessKeySecret: OssData.accessKeySecret,// oss對應令牌密鑰
          stsToken: OssData.securityToken,// oss對應令牌token
        });
        // OssData.path 文件上傳路徑
        let name = OssData.path + uuid.v4() + ".jpg"
        /*
         * name 圖片路徑/名稱
         * file 圖片file文件
         * */
        client.multipartUpload(name, file, {
          progress: function (pro) {
            //獲取進度條的值
            progress(Math.floor(pro * 100))
          },
        }).then(function (res) {
          image.url = "http://img.0q.design/" + res.name
          image.pictureMd5 = JSON.parse(res.etag)
          resolve(image)
        }).catch((err) => {
          reject(err);
        })
      } else {
        reject(res);
      }
    }).catch((err) => {
      reject(err);
    });
  });
}


免責聲明!

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



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