关于前端:阿里Oss图片上传组件

35次阅读

共计 3470 个字符,预计需要花费 9 分钟才能阅读完成。

我的项目在须要应用到大文件上传时,抉择通过前端直连阿里 Oss,个人感觉是个不错的抉择。
一方面不须要本人搭建文件服务器,另一个能节约服务器的带宽压力。
在这记录一下,本人写的 Oss 图片上传组件

获取 Token

虽说是前端直连,然而 Token 还是从后盾获取的。这个时候就须要后盾大哥搞个获取 Oss 的 Token 接口,接下来就能够欢快地上传图片啦。

import {getOssToken} from "@/util/common"; 
const OSS = require("ali-oss");
let client;

created() {getOssToken().then((res) => {
    client = new OSS({
      // yourRegion 填写 Bucket 所在地区。以华东 1(杭州)为例,Region 填写为 oss-cn-hangzhou。region: "oss-cn-hangzhou",
      // 从 STS 服务获取的长期拜访凭证。长期拜访凭证包含长期拜访密钥(AccessKeyId 和 AccessKeySecret)和平安令牌(SecurityToken)。accessKeyId: res.data.accessKeyId,
      accessKeySecret: res.data.accessKeySecret,
      stsToken: res.data.securityToken,
      // 填写 Bucket 名称。bucket: "Bucket",
    });
  });
},

上传图片用到的还是咱们的相熟的 el-upload

<el-upload
  class="avatar-uploader"
  action="#"
  ref="upload"
  v-loading="loading"
  list-type="picture-card"
  :on-success="handleSuccess"
  :before-upload="uploadBefore"
  :on-preview="handlePictureCardPreview"
  :on-remove="handleRemove"
  :file-list="imgList"
>
  <i class="el-icon-plus"></i>
</el-upload>

次要的上传办法就是扭转 el-upload 的默认上传办法

// oss 上传图片
async uploadBefore(file, loading, column) {
  this.loading = true;
  let fileName = this.product + '/' + new Date().getTime() + file.name;
  let result = await client.put("/picture/" + fileName, file);
  this.imgList.push({
    name: fileName,
    url: this.url + fileName,
    fileName: fileName,
  });
  let _this = this;
  setTimeout(function () {_this.loading = false;}, 600);
},

残缺代码如下

<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      ref="upload"
      v-loading="loading"
      list-type="picture-card"
      :on-success="handleSuccess"
      :before-upload="uploadBefore"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="imgList"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog
      :visible.sync="dialogVisible"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {getOssToken} from "@/util/common";
const OSS = require("ali-oss");
let client;

export default {
  name: "uploadImg",
  props: {
    product: {default: function () {return '0'},
      type: String
    }
  },
  created() {
    this.loading = true;
    getOssToken().then((res) => {
      this.loading = false;
      client = new OSS({
        // yourRegion 填写 Bucket 所在地区。以华东 1(杭州)为例,Region 填写为 oss-cn-hangzhou。region: "oss-cn-hangzhou",
        // 从 STS 服务获取的长期拜访凭证。长期拜访凭证包含长期拜访密钥(AccessKeyId 和 AccessKeySecret)和平安令牌(SecurityToken)。accessKeyId: res.data.accessKeyId,
        accessKeySecret: res.data.accessKeySecret,
        stsToken: res.data.securityToken,
        // 填写 Bucket 名称。bucket: "Bucket",
      });
    });
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      src: "",
      imgList: [],
      dialogImageUrl: "",
      url: "picture/",
    };
  },
  methods: {handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // oss 上传图片
    async uploadBefore(file, loading, column) {
      this.loading = true;
      let fileName = this.product + '/' + new Date().getTime() + file.name;
      let result = await client.put("/picture/" + fileName, file);
      this.imgList.push({
        name: fileName,
        url: this.url + fileName,
        fileName: fileName,
      });
      let _this = this;
      setTimeout(function () {_this.loading = false;}, 600);
    },
    uploadAfter(res, loading, column) {},
    handleRemove(file, fileList) {this.imgList.forEach((item, index) => {if (item.fileName == file.fileName) {this.imgList.splice(index, 1);
        }
      });
    },
    clearFiles() {this.imgList = []
      this.$refs.upload.clearFiles();},
    getImList() {return this.imgList;},
    // 上传胜利
    handleSuccess(res, file) {
      this.imagesUrl = res.data;
      // 图片门路返回给父组件
      return this.imgList;
    },
    // 上传胜利之前 对图片格式要求
    beforeAvatarUpload(file) {
      const isPNG = file.type === "image/png";
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPNG && !isJPG) {this.$message.error("上传图片只能是 JPG 格局和 PNG 格局!");
      }
      if (!isLt2M) {this.$message.error("上传图片大小不能超过 2MB!");
      }
      return (isPNG && isLt2M) || (isJPG && isLt2M);
    },
  },
};
</script>

正文完
 0