'413 Error: Uploading to OneDrive API using Sessions

I have a React.js app that is suppose to upload large files to Microsoft OneDrive through their API. I have a test file that is around 3GB (2975226488 bytes) and I am dividing up the file into 327680 bytes at a time. But at the very first range [0-327680] bytes, the API is responding back with 413 error.

Here I am creating a session and getting back a session url.

            const sessResp = await fetch(`https://graph.microsoft.com/v1.0/me/drive/root:/Dropzone/${filename}:/createUploadSession`, {
                method: "POST",
                headers: headers
            });
            const sessParsed = await sessResp.json();

Then I am getting ranges for my file to upload at a time because according to the docs it's suppose to be in multiples of 320Kib (327,680 bytes). Here

            let ranges = []; 
            for (let a = 0; a < filesize; a+=327680) { //320 KiB (327,680 bytes)
                ranges.push(a); 
            }
            ranges.push(filesize);

Then, I am looping through my ranges array and making a request each range at a time to upload my file to OneDrive.

          for (let i = 0; i <= ranges.length; i++) { 
                let uploadSize = filesize > 327680 ? 327680 : ranges[1]; // if filesize is smaller than 327680 then only 2 elements in ranges
                
                let fileheaders = new Headers();
                fileheaders.append("Authorization", bearer);
                fileheaders.append("Content-Type", "application/json");
         
                fileheaders.append("Content-Length", uploadSize);

                fileheaders.append("Content-Range", `bytes ${ranges[i]}-${ranges[i+1]-1}/${filesize}`);
                const resp = await fetch(sessParsed.uploadUrl, {
                    method: "PUT",
                    headers: fileheaders, 
                    body: binaryStr
                });


            }


Solution 1:[1]

Use Streams to upload documents

Over time, this upload feature may not scale well in terms of performance.

Check out this article : https://medium.com/@vecera.petr/how-to-handle-large-file-upload-with-nodejs-express-server-7de9ab3f7af1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jaskaran Deol