vue 大文件分片上传

<template>
</template>

<script>
  import axios from 'axios'
  export default {
    name: 'YunShuBigFileUpload',
    props: {
      fileId: { // 上传 type="file"的id
        type: String
      },
      UploadComplete: { // 完成时执行函数
        type: Function
      },
      ChunkSize: { // 切片大小  单位时MB
        type: Number
      },
      url: { //上传地址
        type: String
      },
      md5: { // 文件的md5值
        type: String
      },
      UploadProgress: { // 上传进度
        type: Function
      }
    },
    watch: {
      md5() {
        this.myMd5 = this.md5
      }
    },
    data() {
      return {
        uploadFile: {
          chunk: 0,
          isLastChunk: false,//是否最后一片文件
          fileName: ''//文件名称
        },
        myMd5: '',
      }
    },
    created() {
      this.myMd5 = this.md5
    },
    methods: {
      chunksFile() {
        // this.fileId : '上传的input元素id'   例如 #input-file-upload
        let file = document.querySelector(this.fileId).files[0], //需要上传的文件
          chunkLength = 0; //文件分片后的长度
        this.uploadFile.fileName = file.name;
        if (file.size > 1024 * 1024 * this.ChunkSize) {
          chunkLength = Math.ceil(file.size / (1024 * 1024 * this.ChunkSize));
        } else {
          chunkLength = 1
        }
        this.uploadFile.chunk === chunkLength - 1 ? this.uploadFile.isLastChunk = true : false;
        let fm = new FormData();
        fm.append('md5', this.myMd5);
        fm.append('size', file.size);
        fm.append('chunk', this.uploadFile.chunk);
        fm.append('chunks ', chunkLength);
        fm.append('fileName ', this.uploadFile.fileName);
        fm.append('file', file.slice(this.uploadFile.chunk * 1024 * 1024 * this.ChunkSize, (this.uploadFile.chunk + 1) * 1024 * 1024 * this.ChunkSize));
        //通过ajax上传分片文件内容
        axios.post(this.url, fm).then((res) => {
          if (res.status == 200) {
            //上传成功,分片加一,上传下一片文件
            this.uploadFile.chunk++
            //上传完最后一片后传输结束
            const pr = parseInt((this.uploadFile.chunk + 1) / chunkLength * 100)
            this.UploadProgress(pr)
            if (this.uploadFile.isLastChunk) {
              this.UploadComplete()
            } else {
              //递归调用上传下一片
              this.chunksFile();
            }
          }
        }).catch((error) => {
          console.log(error)
            this.$Message.warning('上传失败!')
        });
      }
    }
  }
</script>

<style>
</style>

需要和下一篇的《根据文件内容生成md5》配合使用

打工者联盟为了抵抗996、拖欠工资、黑心老板、恶心公司,让我们组成打工者联盟。客观评价自己任职过的公司情况,为其他求职者竖起一座引路的明灯。https://book.employleague.cn/

Vue.js 是一个流行的 JavaScript 框架,用于构建用户界面。如果你需要在 Vue实现大文件分片上传,可以按照以下步骤操作: 1. 安装必要的依赖:你可以使用 `axios` 库来处理文件上传。通过 npm 或 yarn 安装 axios:`npm install axios` 或 `yarn add axios`。 2.Vue 组件中创建文件上传方法:创建一个方法来处理文件上传逻辑。你可以使用 `FormData` 对象来构建表单,并通过 `axios` 发起上传请求。 ```javascript methods: { async uploadFile(file) { const formData = new FormData(); formData.append('file', file); // 将文件添加到表单中 try { await axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', }, onUploadProgress: (progressEvent) => { const progress = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); // 更新进度 console.log(`Upload progress: ${progress}%`); }, }); // 上传成功 console.log('File uploaded successfully!'); } catch (error) { // 处理上传错误 console.error('File upload failed:', error); } }, } ``` 3. 创建文件上传的 HTML 输入元素:在你的模板中添加一个文件输入元素,用于触发文件选择和上传操作。 ```html <input type="file" @change="handleFileUpload" /> ``` 4. 处理文件选择事件:在 Vue 组件的 `methods` 中创建一个处理文件选择事件的方法。 ```javascript methods: { handleFileUpload(event) { const file = event.target.files[0]; this.uploadFile(file); }, } ``` 通过以上步骤,你可以在 Vue.js实现大文件分片上传功能。希望对你有所帮助!如果还有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值