vue 前端阿里雲上傳圖片

1、安裝依賴

npm install ali-oss

2、封裝client

alioss.js

import {getAliOssConfigInfo} from "@/services/my";//獲取阿里雲oss上傳文件配置信息
const OSS = require('ali-oss');

export async  function client() {
  try {
const res = await getAliOssConfigInfo();
if (res.code === 0) {
  const data = res.data.data;
  const client = new OSS({
    region: data.ali_end_point,
    accessKeyId: data.ali_key_id,
    accessKeySecret: data.ali_key_secret,
    bucket: data.ali_bucket
  });
  return client
}
  } catch (err) {
console.log(err);
  }
}

upload.vue

<input type="file" multiple="multiple" @change="doUpload($event)" accept="image/jpeg,image/png,image/gif">
import {client} from '@/utils/alioss'

/**
 * 上傳
 * @param event
 * @returns {Promise<void>}
 */
async doUpload(event) {
  const _this = this;
  const max_file_num = 9;//  文件數量上限
  const files = event.target.files;
  const fileLen = event.target.files.length;
  if (fileLen > max_file_num - _this.img_list.length) {
    this.$dialog.toast({
      mes: `只能選擇${max_file_num - _this.img_list.length}張圖片`,
    });
    return
  }
  _this.$dialog.loading.open('上傳中...');
  if (fileLen && this.img_list.length <= 9) {
    for (let i = 0; i < fileLen; i++) {
      const file = files[i];
      let name = `Uploads/image/${_this.year}-${_this.month}/${new Date().getTime()}${file.name}`
      // 上傳
      try {
        let clientObj = await client();
        let result = await clientObj.multipartUpload(name, file);
        console.log(result.url);
        _this.img_url = result.res.requestUrls[0]
        this.$dialog.loading.close();
        this.$dialog.toast({
          mes: '成功',
          icon: 'success',
          timeout: 1500
        });
      } catch (e) {
        console.log(e);
      }
    }
  }

watch: {
    img_url(val) {
      if (val) {
        this.img_list.push(val);
      }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章