阿里云OSS上传和删除

276 阅读1分钟

安装

npm install ali-oss

引入 uploadAndDeleteOss.js

const OSS = require('ali-oss')
//获取上传参数的接口
import { getAliOssUpload } from '@/api/common'

上传

/*
上传方法
file: 上传的文件对象
*/
export async function uploadOSS(file) {
  const { data } = await getAliOssUpload()
  console.log(data)
  const client = new OSS({
    // yourRegion填写Bucket所在地域。以华东1(杭州)为例,Region填写为oss-cn-hangzhou。
    region: 'oss-cn-hangzhou',
    // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
    accessKeyId: data.AccessKeyId,
    accessKeySecret: data.AccessKeySecret,
    // 从STS服务获取的安全令牌(SecurityToken)。
    stsToken: data.SecurityToken,
    // 填写Bucket名称,例如examplebucket。
    bucket: 'yangdev',
    refreshSTSToken: async() => {
    // 向您搭建的STS服务获取临时访问凭证。
      const info = await getAliOssUpload()
      return {
        accessKeyId: info.data.AccessKeyId,
        accessKeySecret: info.data.AccessKeySecret,
        stsToken: info.SecurityToken
      }
    },
    // 刷新临时访问凭证的时间间隔,单位为毫秒。
    refreshSTSTokenInterval: 300000
  })
  // 上传到bucket中的/yang/文件夹 名字命名为new Date().getTime() + file.name
  const result = client.put(`/yang/${new Date().getTime() + file.name}`, file.raw || file)
  return result
}

删除

/*
删除文件
ObjKey: 上传文件成功后,OSS返回的name 根据这个去删除
*/
export async function delOSS(config, objKey) {
  const { data } = await getAliOssUpload()
  console.log(data)
  const client = new OSS({
    // yourRegion填写Bucket所在地域。以华东1(杭州)为例,Region填写为oss-cn-hangzhou。
    region: 'oss-cn-hangzhou',
    // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
    accessKeyId: data.AccessKeyId,
    accessKeySecret: data.AccessKeySecret,
    // 从STS服务获取的安全令牌(SecurityToken)。
    stsToken: data.SecurityToken,
    // 填写Bucket名称,例如examplebucket。
    bucket: 'yangdev',
    refreshSTSToken: async() => {
      // 向您搭建的STS服务获取临时访问凭证。
      const info = await getAliOssUpload()
      return {
        accessKeyId: info.data.AccessKeyId,
        accessKeySecret: info.data.AccessKeySecret,
        stsToken: info.SecurityToken
      }
    },
    // 刷新临时访问凭证的时间间隔,单位为毫秒。
    refreshSTSTokenInterval: 300000
  })
  console.log(objKey)
  const result = client.delete(objKey)
  return result
}

封装element的upload组件 ImageUpload.vue

<!-- 我的页面 -->
<template>
  <div class="page">
    <div v-viewer="optionsImage">
      <el-upload
        action="#"
        :class="{ hideUploadBtn: hide }"
        :file-list="fileList"
        :limit="limitCount"
        list-type="picture-card"
        :http-request="upload"
        :before-upload="beforeUploadFile"
        :on-success="handleSuccess"
      >
        <i slot="default" class="el-icon-plus" />
        <div slot="file" slot-scope="{ file }" style="position: relative">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete" />
          </span>
        </div>
      </el-upload>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
// 例如:import 《组件名称》 from '《组件路径》'
import { uploadOSS, delOSS } from '@/utils/uploadAndDeleteOss'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  model: {
    prop: 'images',
    event: 'change'
  },
  props: {
    images: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    // 这里存放数据
    return {
      optionsImage: {
        inline: false
      }, // viewer 图片查看器配置
      fileList: [], // 文件列表
      limitCount: 6, // 最大上传数
      hide: false, // 是否隐藏上传按钮
      maxSize: 5 * 1024 * 1024, // 单张图片最大质量
      imgOssList: [], // 图片上传到OSS的路径集合
      imgOssName: [], // 图片上传到OSS的名字集合 删除图片时用
      fileNameList: [] // 图片在本地的名字集合
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成(可以访问当前this实例)
  created() {},
  // 生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能,这个函数会触发
  // 方法集合
  methods: {
    // 自定义上传图片
    async upload(file) {
      try {
        const imgObj = await uploadOSS(file.file)
        console.log(imgObj)
        this.imgOssName.push(imgObj.name)
        this.fileNameList.push(file.file.name)
        if (imgObj.url) {
          this.imgOssList.push(imgObj.url)
          this.$emit('change', this.imgOssList)
        }
      } catch (err) {
        this.$message({
          type: 'error',
          message: '上传失败,请稍后再试'
        })
        console.log(err)
      }
    },
    // 文件上传前钩子
    beforeUploadFile(file) {
      return new Promise((resolve, reject) => {
        if (file.size > this.maxSize) {
          this.$message({
            type: 'error',
            message: '单张支付凭证不能大于5M'
          })
          return reject(false)
        } else {
          return resolve(true)
        }
      })
    },
    // 文件上传成功钩子
    handleSuccess(res, file, fileList) {
      this.hide = fileList.length >= this.limitCount
      this.fileList = fileList
    },
    // 删除图片钩子
    handleRemove(file) {
      // 获取点击删除图片的索引 并删除在本地的路径和oss路径
      const index = this.fileNameList.indexOf(file.name)
      this.fileList.splice(index, 1)
      this.imgOssList.splice(index, 1)
      this.hide = this.fileList.length >= this.limitCount
      delOSS(this.ossConfig, this.imgOssName[index])
    }
  }
}
</script>

<style lang='scss' scoped>
//@import url(); 引入公共css类
.el-upload-list__item-delete {
  display: block;
  font-size: 20px;
}
</style>

使用

<ImageUpload v-model="images">