二次封装el-upload实现阿里云OSS上传

背景:

由于公司服务器带宽受限,但是升级带宽费用较为昂贵,故直接上传文件至oss(上传时长=文件大小(M)/ 带宽(M)*8)s,公司项目对于文件上传需求比较强烈,且量很大,目前服务器带宽为4M,通过服务器上传速度非常感人......

程序猿的一贯作风,话不多数上代码:
<template>
    <el-upload
      action="#"
      :data="{ type: `${type}` }"
      :show-file-list="false"
      :accept="accept"
      :multiple="multiple"
      :auto-upload="false"
      :file-list="fileList"
      :on-change="resureUpload"
    >
      <div class="fileWrapper">
        <div style="text-align: center">
          <el-icon><Plus /></el-icon>
          <div style="font-size: 10px">请上传附件</div>
        </div>
      </div>
    </el-upload>
  </div>
</template>

<script setup>
import { ref, defineProps, toRefs, defineEmits } from 'vue'
import getFileType from '../utils/getFileType'
import OSS from 'ali-oss'
import { v4 as uuidv4 } from 'uuid'
const client = new OSS({
  region: '你的region', // 服务器集群地区
  accessKeyId: '你的', // accessKeyId
  accessKeySecret: '你的', // accessKeySecret
  bucket: '你的' // 阿里云上存储的 Bucket名称
})
const uploadLoading = ref()
const fileList = ref([])
const attchmentArray = ref([])
const props = defineProps({
  fileListString: { type: String, default: () => null },
  accept: { type: String, default: () => 'image/*' },
  type: { type: String, default: () => 'order' },
  multiple: { type: Boolean, default: () => true }
})
const { fileListString, accept, type, multiple } = toRefs(props)
attchmentArray.value = fileListString.value
  ? JSON.parse(fileListString.value)
  : []
const emits = defineEmits(['fileChanged'])
const resureUpload = (file, files) => {
  fileList.value = files
  let blob = new Blob([file.raw])
  handlerUpload(blob, file.name)
}
const handlerUpload = (file, name) => {
  if (!uploadLoading.value) {
    uploadLoading.value = ElLoading.service({
      text: `文件上传中……`,
      background: 'rgba(0, 0, 0, 0.2)'
    })
  }
  let date = new Date()
  //   console.log(date.toISOString().substring(0, 10))
  let filePath = `/aztg/${type.value}/${date
    .toISOString()
    .substring(0, 10)}/${uuidv4()}_${name}`
  client
    .put(filePath, file)
    .then(response => {
      attchmentArray.value.push(response.url)
      if (
        uploadLoading.value &&
        fileList.value.length == attchmentArray.value.length
      ) {
        uploadLoading.value.close()
        uploadLoading.value = null
        emits('fileChanged', attchmentArray.value)
      }
    })
    .catch(err => {
      ELMessage.error(err)
      fileList.value.splice(0, 1)
      if (
        uploadLoading.value &&
        fileList.value.length == attchmentArray.value.length
      ) {
        emits('fileChanged', attchmentArray.value)
        uploadLoading.value.close()
        uploadLoading.value = null
      }
    })
}
// 删除
const handleRemove = index => {
  attchmentArray.value.splice(index, 1)
  emits('fileChanged', attchmentArray.value)
}
// 下载文件
const handleDownload = file => {
  const ele = document.createElement('a')
  ele.href = file
  ele.target = '_blank'
  ele.download = '下载文件'
  document.body.appendChild(ele)
  ele.click()
  document.body.removeChild(ele)
}
// 预览
const previewUrl = ref(null)
const previewVisible = ref(false)
const handlePreview = file => {
  if (getFileType(file) == 'video') {
    previewUrl.value = file
    previewVisible.value = true
  } else {
    handleDownload(file)
  }
}
</script>
<style lang="scss" scoped>
.outer {
  display: flex;
}
.fileWrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
  margin: 5px 5px 0 0;
  border: 1px solid #eee;

  .uploadoperater {
    position: absolute;
    top: 2px;
    right: 2px;
    background-color: #fff;
    height: 15px;
    line-height: 15px;
    text-align: center;
    width: 15px;
    cursor: pointer;
    z-index: 999;
    &:hover {
      font-weight: bold;
    }
  }
  .uploadFile {
    width: 100px;
    height: 100px;
  }
}
.uploader {
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>

由于设计公司内部一些敏感信息,故代码并非完整,但是稍作修改既能使用,当然仅有此代码还不能实现功能,在此之前需要做一些准备工作,

1 在阿里云上购买OSS服务然后进行配置
1.1 创建Bucket
  • Bucket名称自定义
  • 地域为购买时选择的地域
  • 权限改为公共读写
  • 其余可以默认
1.2 权限管理->跨域设置
  • 创建规则
  • 来源可以指定也可以用*指定全部来源
  • 允许methods可以指定也可以全部勾选
  • 允许Headers写*
  • 其余默认即可
1.3 创建 AccessKey
在阿里云头像处点击AccessKey管理
根据自身需求创建获取AccessKey
2 Vue中使用OSS
2.1 安装
npm i ali-oss -D (安装到生产依赖)
2.2 引入

const OSS = require(“ali-oss”);

文章写得比较粗糙,但是很实用,欢迎大佬知道提建议,不喜勿喷

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值