Vue.js 实现分片上传的示例代码

242 阅读1分钟
<template>
  <div>
    <input type="file" @change="selectFile" ref="fileInput" />
    <button @click="uploadFile">上传文件</button>
    <div>{{ progress }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      file: null,
      progress: 0
    };
  },
  methods: {
    selectFile(event) {
      this.file = event.target.files[0];
    },
    uploadFile() {
      const chunkSize = 1024 * 1024; // 每个分片大小为 1MB
      const totalSize = this.file.size;
      let start = 0;
      let end = chunkSize;
      let chunkIndex = 0;
      const fileReader = new FileReader();

      fileReader.onload = (event) => {
        // 将分片数据发送到服务器
        // 这里使用 axios 发送分片数据,具体实现可以根据实际情况进行修改
        axios.post("/upload", {
          file: event.target.result,
          index: chunkIndex,
          total: Math.ceil(totalSize / chunkSize)
        }).then(() => {
          // 如果还有分片数据,继续发送下一片
          if (end < totalSize) {
            start = end;
            end = start + chunkSize;
            chunkIndex++;
            fileReader.readAsArrayBuffer(this.file.slice(start, end));
            this.progress = Math.floor((end / totalSize) * 100);
          } else {
            // 所有分片上传完毕,进行合并操作
            axios.post("/merge", {
              fileName: this.file.name,
              total: Math.ceil(totalSize / chunkSize)
            });
            this.progress = 100;
          }
        });
      };

      fileReader.readAsArrayBuffer(this.file.slice(start, end));
    }
  }
};
</script>

这段代码实现了分片上传的功能,通过选择文件和点击上传按钮触发上传事件。在上传事件中,将文件分为多个分片,并逐个发送到服务器。如果还有分片数据,继续发送下一片;如果所有分片都上传完毕,则触发合并操作。在上传过程中,还会实时更新上传进度,将当前上传进度展示在页面上。

需要注意的是,这段代码只是一个示例,实际使用时需要根据具体情况进行修改,例如根据后端 API 的接口来实现分片数据的发送和合并操作。同时,还需要进行一些异常处理和错误处理,确保上传过程的稳定性和可靠性。