html 阿里云OSS多文件上传组件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 阿里云OSS多文件上传组件相关的知识,希望对你有一定的参考价值。

<template>
  <el-upload
    list-type="picture-card"
    name="image"
    :multiple="true"
    :limit="limit"
    :file-list="imageList"
    :before-upload="beforeUpload"
    :http-request="uploadImg"
    :on-exceed="handleExceed"
    :on-success="onUploadSuccess"
    :on-remove="onUploadRemove"
    action="/admin/upload"
  >
    <i class="el-icon-plus"></i>
    <div class="el-upload__tip" slot="tip">只支持 jpg/png 文件,大小最大为 10M</div>
  </el-upload>
</template>

<script>
import Cookies from 'js-cookie'
export default {
  name: 'multipleUpload',
  props: {
    image: {
      type: Array,
      default: []
    },
    value: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      imageList: [],
      imageKeyList: []
    }
  },
  created() {
    this.imageList = []
    this.imageKeyList = []
    this.imageList.push(...this.image)
    this.imageKeyList.push(...this.value)
  },
  watch: {
    image(val) {
      this.imageList = val
      this.imageKeyList = val.map((item) => {
        return item.key || item.response
      })
    }
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件,本次选择了 ${
          files.length
        } 个文件,共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeUpload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      return true
    },
    onUploadSuccess(response, file, fileList) {
      this.imageList = fileList
      this.imageKeyList.push(response)
      this.$emit('input', this.imageKeyList)
    },
    onUploadRemove(file, fileList) {
      this.imageList = fileList
      this.imageKeyList = fileList.map((item) => {
        return item.key || item.response
      })
      this.$emit('input', this.imageKeyList)
    },
    async uploadImg(item) {
      const OSS = require('ali-oss')
      const client = new OSS({
        region: 'oss-cn-hangzhou',
        endpoint: Cookies.get('msk_oss_end_point'),
        accessKeyId: Cookies.get('msk_oss_key'),
        accessKeySecret: Cookies.get('msk_oss_secret'),
        bucket: Cookies.get('msk_oss_bucket')
      })

      const filename = Date.parse(new Date())
      const fileExt = item.file.name
        .toLowerCase()
        .split('.')
        .splice(-1)
      const newFilename =
        filename +
        '-' +
        Math.floor(Math.random() * Math.floor(999999)) +
        '.' +
        fileExt[0]
      const result = await client.put(newFilename, item.file)

      return result.url
    }
  }
}
</script>

<style>
</style>

以上是关于html 阿里云OSS多文件上传组件的主要内容,如果未能解决你的问题,请参考以下文章

有谁使用过阿里云oss的吗?多文件多图时怎么上传

微信小程序直接上传文件到阿里云OSS组件封装

微信小程序直接上传文件到阿里云OSS组件封装

vue 上传文件到 阿里云OSS,并获取上传进度

vue + elementUi + upLoadIamge组件 上传文件到阿里云oss

阿里云里oss图片上传的复制文件地址太长了,怎么办?