vue element+oss上传文件

429 阅读1分钟

1.引入oss

npm i ali-oss -D

2.新建aliyun.oss.client.js

/*
 * 阿里云oss上传工具
 *
 * @description conf: {
                region: null,
                accessKeyId: null,
                accessKeySecret: null,
                bucket: null,
                stsToken: null
            }
 */
import OSS from 'ali-oss';
export default (conf) => {
    return new OSS(conf);
};

3.在需要使用的文件,例如about.vue

<template>
  <div class="about">
    <el-button type="success" @click="init">获取上传信息</el-button>
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      drag
      :multiple="false"
      :http-request="uploadHttp"
      list-type="picture"
    >
      <div class="el-upload__text">
        <el-button type="warning">点击上传</el-button>
      </div>
    </el-upload>
    <img class="ossimg" :src="avatar" alt="" />

  </div>
</template>

<script>
import ossClient from "@/assets/js/aliyun.oss.client";
export default {
  data() {
    return {
      uploadConf: {
        region: null,
        accessKeyId: null,
        accessKeySecret: null,
        bucket: null,
        stsToken: null,
      },
      avatar: "",
    };
  },
  methods: {
    init() {
      this.$api
        .getOssAuth()  //通过请求接口获取上传信息
        .then((res) => {
          if (res.data.success) {
            this.uploadConf.region = "oss-cn-beijing";
            this.uploadConf.accessKeyId = res.data.data.accessKeyId;
            this.uploadConf.accessKeySecret = res.data.data.accessKeySecret;
            this.uploadConf.bucket = res.data.data.bucket;
            this.uploadConf.stsToken = res.data.data.securityToken;
            this.uploadConf.defaultPath = res.data.data.defaultPath;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 阿里云OSS上传
    uploadHttp({ file }) {
      const imgName = this.uploadConf.defaultPath;
      const fileName = `${imgName}/${Date.parse(new Date())}`; //定义唯一的文件名
      ossClient(this.uploadConf)
        .put(fileName, file, {
          ContentType: "image/jpeg",
        })
        .then(({ res, url, name }) => {
          if (res && res.status == 200) {
            console.log(`上传图片成功`, res, url, name);
            this.avatar = url;  //上传成功后返回的文件路径
          }
        })
        .catch((err) => {
          console.log(`上传图片失败`, err);
        });
    },
  },
};
</script>

<style scoped lang="stylus">
.about {
  text-align center
}
.ossimg {
  max-width 500px
}
.avatar-uploader {
  width 125px
  height 45px
}
>>>.avatar-uploader .el-upload {
  width 125px
  height 45px
  border-radius 6px
  cursor pointer
  position relative
  overflow hidden
}
.el-upload__text {
  width 125px
  height 45px
}
</style>