Upload ElementUI component pictures to Qiniu Cloud

Reference file (Qiniu cloud upload address)insert image description here

注意:上传的域名地址根据自己实际所在地址选择


The code of the entire component (built-in comment information)

<template>
  <div>
    <!-- 
      action="https://upload-z2.qiniup.com"       根据自己所在位置选择七牛云上传地址
      :data="dataToken"                           将图片回调获取的token及key以参数的形式携带给七牛云
      :before-upload="beforeUpload"               上传文件之前的钩子,完成与后端获取七牛云回调的外链地址及需要携带的token
      :on-success="handleAvatarSuccess"           上传七牛云成功之后的回调函数
    -->
    <el-upload
      class="avatar-uploader"
      action="https://upload-z2.qiniup.com"
      :data="dataToken"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleAvatarSuccess"
    >
      <el-image v-if="imageUrl" :src="imageUrl" class="avatar"> </el-image>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>
  
  <script>
export default {
    
    
  data() {
    
    
    return {
    
    
      imageUrl: "", // 回调需要显示的图片地址
      dataToken: {
    
    
        //传到七牛云所需要的token及key
        token: "",
        key: "",
      },
      domain: "", //外链地址
    };
  },
  mounted() {
    
    },
  methods: {
    
    
    // 获取上传所需要的token
    async beforeUpload(file) {
    
    
      // 通过请求后端获取七牛token及外链地址
      const result = await this.$API.baseData.qiniuyunList();
      // console.log(result);
      this.dataToken.token = result.data.token;
      this.dataToken.key = Date.now() + "." + file.name.split(".")[1]; // 通过时间戳及文件名拼接为独立的key(既是文件名称)
      this.domain = result.data.domain;
    },

    // 回调图片地址
    handleAvatarSuccess(res) {
    
    
      this.imageUrl = this.domain + "/" + res.key; // 将成功返回的地址拼接成可访问的链接地址
      this.$emit("sendImg", this.imageUrl); // 将图片地址发送到需要使用的组件中
    },
    // 编辑图片
    handleImg(e) {
    
    
      // console.log(e);
      this.imageUrl = e;
    },
  },
};
</script>
  
  <style lang="scss">
.avatar-uploader .el-upload {
    
    
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    
    
  border-color: #409eff;
}
.avatar-uploader-icon {
    
    
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
    
    
  width: 178px;
  height: 178px;
  display: block;
}
</style>
    

组件可直接使用,备注较为清晰


The file is for your own reference only (study notes)!

Guess you like

Origin blog.csdn.net/qq_44760955/article/details/130872304