javascript - 使用axios上传 block 文件

标签 javascript vue.js vuejs2 axios

我遇到了一个问题,希望有人能帮助我。 我需要用axios实现文件分块上传,需要一个个分块发送到我的服务器。所以新的 axios 请求应该在前一个请求完成之后发生。 现在,请求没有按顺序发送。 我的代码如下:

  addChunk(file) { // I receive file from my file uploader 
  this.getBase64(file[0].file).then((base64) => {
    this.convertChunks = base64.replace(base64.substring(0, base64.search(',') + 1), '')
    this.convertedArr = this.convertChunks .match(/.{1,500000}/g) //here I convert it into base64 with helper function
  })
  for (let i in this.convertedArr) {
    if (this.uploadSuccess === false) return null
      axios({
        url: `${domain}`,
        method: 'POST',
        data: [this.convertedArr[i]]
      })
        .then(() => {
          if (parseInt(i) === this.convertedArr.length - 1) {
            this.nextFunction()  //after the last chunk is sent successfully, i need to call another function
          }
        })
        .catch((error) => {
          console.log(error)
        })
  }
},

最佳答案

使用 async/await 语法使您的方法可以等待 axios 请求完成。

同时切换到 for...of 而不是 for...in。后者用于循环遍历对象的可枚举属性,尽管它可用于数组,但在顺序很重要时应避免使用。

通过遍历 this.convertedArr.entries() 展开 for...of。这将为数组中的每个项目创建一个包含 [ index, value ] 的数组,因此您可以使用索引。

使用 try...catch...finally,您可以捕获等待的函数调用可能产生的任何错误。 finally 部分用于确保在请求成功或失败时调用该部分。

async addChunk(file) { // I receive file from my file uploader 
  this.getBase64(file[0].file).then((base64) => {
      this.convertChunks = base64.replace(base64.substring(0, base64.search(',') + 1), '')
      this.convertedArr = this.convertChunks.match(/.{1,500000}/g) //here I convert it into base64 with helper function
  })

  for (const [ i, item ] of this.convertedArr.entries()) {
    if (this.uploadSuccess === false) return null

    try {
      await axios({
        url: `${domain}`,
        method: 'POST',
        data: [item]
      });
    } catch(error) {
      console.log(error)
    } finally {
      if (parseInt(i) === this.convertedArr.length - 1) {
        this.nextFunction();
      }
    }
  }
}

关于javascript - 使用axios上传 block 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64990763/

相关文章:

javascript - 在输入字段上设置最大和最小限制?

javascript - 如何停止在 Electron 应用程序上创建空日志目录

javascript - react native react-native-sqlite-storage不返回结果

javascript - Vue.js - 在组件中使用父数据

javascript - Vue - 无法在我的 mixin 文件中使用或访问 this.$router 或 vue 实例

javascript - 如何使 Vue.js 中的值成为非响应式的?

javascript - VueJS 扩展组件 : remove parent's property

javascript - 检索 angularjs 指令中的绑定(bind)值

javascript - datejavascript 将数值转换为时间值

javascript - 有没有办法将父 css 泄漏到 Vue 中的子组件?