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


import {client} from '@/utils/alioss'

/**
 * 上传
 * @param event
 * @returns {Promise}
 */
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);
      }
    }
}

你可能感兴趣的:(vue.js,阿里云oss)