使用XmlHttpRequests

时间:2019-05-16 20:34:01

标签: javascript xmlhttprequest

我正在尝试使用XmlHttpRequest下载多个文件,但是无法处理异步方法。如何获得与urls数组相同的结果。

urls = ['url1','url2','url3']

获得结果: ['url2','url1','url3']

  function downloadFiles(urls, callback) {
  var buffer = []
  var ind = 0
  for (var u in urls) {
    var xhr = new XMLHttpRequest()
    xhr.open('GET', urls[u], true)
    xhr.responseType = 'arraybuffer'
    xhr.onload = function (e) {
      if (this.status == 200 || this.status == 304) {
        var uInt8Array = new Uint8Array(this.response)
        var i = uInt8Array.length
        var binaryString = new Array(i)
        while (i--)
        binaryString[i] = String.fromCharCode(uInt8Array[i])
        var data = binaryString.join('')
        var base64 = window.btoa(data)
        var fileName = urls[ind].substr(urls[ind].indexOf('.jpg')-20, 24)
        //var downloadedFile = createTempFolder() + fileName;
        //writeFile(downloadedFile, base64)
        buffer[ind] = downloadedFile
        if (ind === urls.length - 1) {
          return callback(buffer)
        }
        ind++
      }
    };
    xhr.send()
  }
}

0 个答案:

没有答案