For loop inside xhr onreadystatechange request not working

62 Views Asked by At

I'm uploading files through google drive API resumable upload as multiple chunks to monitor the upload state. So I used for loop to request for each chunk. The full code is as below :

xhr.onreadystatechange = async function () {

    if (this.readyState == this.HEADERS_RECEIVED) {
      // Get the raw header string
      var headers = xhr.getAllResponseHeaders();
      // Convert the header string into an array
      // of individual headers
      var arr = headers.trim().split(/[\r\n]+/);
      // Create a map of header names to values
      var headerMap = {};
      arr.forEach(function (line) {
        var parts = line.split(": ");
        var header = parts.shift();
        var value = parts.join(": ")
        headerMap[header] = value;
      });
      const resumableURI = headerMap.location
      console.log('resumable uri : ' + resumableURI)
      const fileChunks = divideFileInChunks(req.files.muploadedFile.data)
      
      try {
        for( let i =0; i<fileChunks.length; i+=1) {
           console.log('inside for loop');
             axios.put(`${resumableURI}`,  bufferToStream(buffer),
              {
               headers: {
                 Authorization: `Bearer ${accessToken }`,
               "Content-Length": req.files.muploadedFile.size,
               "Content-Range": `bytes ${fileChunks.start}-${fileChunks.end }/${req.files.muploadedFile.size}`
                 } 
             }).then( resp => {
                    console.log(resp.data);
                  }).catch( e => console.log(e))
            return res.status(200).json({'message' : `${i+1} Chunk Uploaded of ${fileChunks.length}`})             
            }
        } catch (f) {
        res.send(f.message);
      }

             
    } 
  };
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("Authorization", `Bearer ${accessToken }`);
xhr.send( //3
    JSON.stringify({
      name: req.files.muploadedFile.name,
      mimeType: req.files.muploadedFile.mimetype, 
    })
  );

});

The problem here is the code inside for loop is not executing.

0

There are 0 best solutions below