代码改变世界

大文件el-upload分片上传到七牛

2024-02-07 15:23  法子  阅读(167)  评论(0编辑  收藏  举报

参考: https://blog.csdn.net/So_cute_girl/article/details/118606647

需要自定义上传方法http-request,用七牛的分片上传

<template>
  <el-upload drag :limit="1" action="https://up.qiniup.com" :multiple="false"
    accept=".mp4" :data="uploadForm" :file-list="fileListVideo" :before-upload="beforeUpload"
    :on-exceed="onExceedUploadVideo" :on-remove="onRemoveUploadVideo" :on-success="onSuccessUploadVideo"
    :on-change="onChangeUploadVideo" :http-request="uploadHttpRequestVideo">
    <i class="el-icon-upload" />
    <div class="el-upload__text">
      将视频拖到此处,或
      <em>点击上传</em>
    </div>
    <div slot="tip" class="tip-text">
      上传一个,视频大小不超过1.5G,支持mp4格式。
    </div>
  </el-upload>
</template>

<script>

import { getQiniuToken } from "@/utils/commons";
import * as qiniu from "qiniu-js";

export default {
  data () {
    return {
      fileList: [],
      uploadForm: {
        token: "",
      },
      maxSize: 1.5 * 1024 * 1024 * 1024,
      subscription: null
    };
  },
  mounted () {
    this.getQiniuToken()
  },
  beforeUnmount () {
    this.subscription && this.subscription.unsubscribe()
  },
  methods: {
    async getQiniuToken () {
      this.uploadForm.token = await getQiniuToken();
    },
    beforeUpload (file) {
      // 重命名
      this.uploadForm.key = `${file.uid}_${Math.floor(Math.random() * 10000)}.${file.name.split('.').pop()}`
    },
    onExceedUpload () {
      // 超过了上传数量
      this.$message({
        message: '最多上传一个视频',
        type: "warning"
      });
    },
    onRemoveUpload (file, fileList) {
      // 删除
      this.fileList = fileList;
    },
    onSuccessUpload (res, file) {
      // 上传成功
    },
    onChangeUpload (file, fileList) {
      // 文件大小
      if (file.size > this.maxSize) {
        this.$message({
          message: '文件超过1.5G',
          type: "error"
        });
        return false
      }
      this.fileList = fileList;
    },
    uploadHttpRequest (option) {
      const observable = qiniu.upload(option.file, this.uploadForm.key, this.uploadForm.token)
      this.subscription = observable.subscribe({
        next (res) {
          option.onProgress({ percent: res.total.percent })
        },
        error (err) {
          option.onError(err)
        },
        complete (res) {
          option.onSuccess(res)
        }
      })
      return this.subscription
    }
  }
};
</script>