1
项目在需要使用到大文件上传时,选择通过前端直连阿里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>

yiyou12138
129 声望9 粉丝