Programmatically Uploading Large Files In SharePoint Online

Introduction

By default, client-side scripting has some restrictions while posting large sizes of data in different browsers.

While using Angular HTTP post to upload a file, I’m facing an issue --  more than a 100MB file upload breaks in some of the browsers like Chrome, Firefox, etc.

Now, I’m using file chunking to post the file as split chunks by SharePoint REST API.

Angular + SharePoint Large file upload

Follow the below-listed steps to upload the large files.

Step1

Create a "File upload" component template like below.

  1. <input class="upload form-control" id="DocUploader" placeholder="Upload file" type="file" (change)="UploadFile($event)">  

Step2

Below is the TypeScript code for the file upload component.

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. @Component({  
  5.     selector: 'app-fileupload',  
  6.     templateUrl: './fileupload.component.html',  
  7. })  
  8. export class FileUploadComponent {  
  9.     UploadFile(event: any) {  
  10.         let fileList: FileList = event.target.files;  
  11.         if (fileList.length != 0) {  
  12.             this.fileUploadService.fileUpload(fileList[0].name, "Documents", fileList[0].name).then(addFileToFolder => {  
  13.                 console.log("File Uploaded Successfully");  
  14.             }).catch(addFileToFolderError => {  
  15.                 console.log(addFileToFolderError);  
  16.             });  
  17.         }  
  18.     }  
  19. }  

Step3

The important part of chunk based file upload implementation is Angular service. FileUploadService code is mentioned below.

  1. import {  
  2.     Injectable,  
  3.     EventEmitter  
  4. } from '@angular/core';  
  5. declare  
  6. var _spPageContextInfo: any;  
  7. declare  
  8. var SP: any;  
  9. @Injectable()  
  10. export class FileUploadService {  
  11.     public siteUrl: string = _spPageContextInfo.webAbsoluteUrl;  
  12.     public siteRelativeUrl: string = _spPageContextInfo.webServerRelativeUrl != "/" ? _spPageContextInfo.webServerRelativeUrl : "";  
  13.     public fileUpload(file: any, documentLibrary: string, fileName: string) {  
  14.         return new Promise((resolve, reject) => {  
  15.             this.createDummyFile(fileName, documentLibrary).then(result => {  
  16.                 let fr = new FileReader();  
  17.                 let offset = 0;  
  18.                 // the total file size in bytes...  
  19.                 let total = file.size;  
  20.                 // 1MB Chunks as represented in bytes (if the file is less than a MB, seperate it into two chunks of 80% and 20% the size)...  
  21.                 let length = parseInt(1000000) > total ? Math.round(total * 0.8) : parseInt(1000000);  
  22.                 let chunks = [];  
  23.                 //reads in the file using the fileReader HTML5 API (as an ArrayBuffer) - readAsBinaryString is not available in IE!  
  24.                 fr.readAsArrayBuffer(file);  
  25.                 fr.onload = (evt: any) => {  
  26.                     while (offset < total) {  
  27.                         //if we are dealing with the final chunk, we need to know...  
  28.                         if (offset + length > total) {  
  29.                             length = total - offset;  
  30.                         }  
  31.                         //work out the chunks that need to be processed and the associated REST method (start, continue or finish)  
  32.                         chunks.push({  
  33.                             offset,  
  34.                             length,  
  35.                             method: this.getUploadMethod(offset, length, total)  
  36.                         });  
  37.                         offset += length;  
  38.                     }  
  39.                     //each chunk is worth a percentage of the total size of the file...  
  40.                     const chunkPercentage = (total / chunks.length) / total * 100;  
  41.                     if (chunks.length > 0) {  
  42.                         //the unique guid identifier to be used throughout the upload session  
  43.                         const id = this.guid();  
  44.                         //Start the upload - send the data to S  
  45.                         this.uploadFile(evt.target.result, id, documentLibrary, fileName, chunks, 0, 0, chunkPercentage, resolve, reject);  
  46.                     }  
  47.                 };  
  48.             })  
  49.         });  
  50.     }  
  51.     createDummyFile(fileName, libraryName) {  
  52.         return new Promise((resolve, reject) => {  
  53.             // Construct the endpoint - The GetList method is available for SharePoint Online only.  
  54.             var serverRelativeUrlToFolder = "decodedurl='" + this.siteRelativeUrl + "/" + libraryName + "'";  
  55.             var endpoint = this.siteUrl + "/_api/Web/GetFolderByServerRelativePath(" + serverRelativeUrlToFolder + ")/files" + "/add(overwrite=true, url='" + fileName + "')"  
  56.             const headers = {  
  57.                 "accept""application/json;odata=verbose"  
  58.             };  
  59.             this.executeAsync(endpoint, this.convertDataBinaryString(2), headers).then(file => resolve(true)).catch(err => reject(err));  
  60.         });  
  61.     }  
  62.     // Base64 - this method converts the blob arrayBuffer into a binary string to send in the REST request  
  63.     convertDataBinaryString(data) {  
  64.         let fileData = '';  
  65.         let byteArray = new Uint8Array(data);  
  66.         for (var i = 0; i < byteArray.byteLength; i++) {  
  67.             fileData += String.fromCharCode(byteArray[i]);  
  68.         }  
  69.         return fileData;  
  70.     }  
  71.     executeAsync(endPointUrl, data, requestHeaders) {  
  72.         return new Promise((resolve, reject) => {  
  73.             // using a utils function we would get the APP WEB url value and pass it into the constructor...  
  74.             let executor = new SP.RequestExecutor(this.siteUrl);  
  75.             // Send the request.  
  76.             executor.executeAsync({  
  77.                 url: endPointUrl,  
  78.                 method: "POST",  
  79.                 body: data,  
  80.                 binaryStringRequestBody: true,  
  81.                 headers: requestHeaders,  
  82.                 success: offset => resolve(offset),  
  83.                 error: err => reject(err.responseText)  
  84.             });  
  85.         });  
  86.     }  
  87.     //this method sets up the REST request and then sends the chunk of file along with the unique indentifier (uploadId)  
  88.     uploadFileChunk(id, libraryPath, fileName, chunk, data, byteOffset) {  
  89.         return new Promise((resolve, reject) => {  
  90.             let offset = chunk.offset === 0 ? '' : ',fileOffset=' + chunk.offset;  
  91.             //parameterising the components of this endpoint avoids the max url length problem in SP (Querystring parameters are not included in this length)  
  92.             let endpoint = this.siteUrl + "/_api/web/getfilebyserverrelativeurl('" + this.siteRelativeUrl + "/" + libraryPath + "/" + fileName + "')/" + chunk.method + "(uploadId=guid'" + id + "'" + offset + ")";  
  93.             const headers = {  
  94.                 "Accept""application/json; odata=verbose",  
  95.                 "Content-Type""application/octet-stream"  
  96.             };  
  97.             this.executeAsync(endpoint, data, headers).then(offset => resolve(offset)).catch(err => reject(err));  
  98.         });  
  99.     }  
  100.     //the primary method that resursively calls to get the chunks and upload them to the library (to make the complete file)  
  101.     uploadFile(result, id, libraryPath, fileName, chunks, index, byteOffset, chunkPercentage, resolve, reject) {  
  102.         //we slice the file blob into the chunk we need to send in this request (byteOffset tells us the start position)  
  103.         const data = this.convertFileToBlobChunks(result, byteOffset, chunks[index]);  
  104.         //upload the chunk to the server using REST, using the unique upload guid as the identifier  
  105.         this.uploadFileChunk(id, libraryPath, fileName, chunks[index], data, byteOffset).then(value => {  
  106.             const isFinished = index === chunks.length - 1;  
  107.             index += 1;  
  108.             const percentageComplete = isFinished ? 100 : Math.round((index * chunkPercentage));  
  109.             //More chunks to process before the file is finished, continue  
  110.             if (index < chunks.length) {  
  111.                 this.uploadFile(result, id, libraryPath, fileName, chunks, index, byteOffset, chunkPercentage, resolve, reject);  
  112.             } else {  
  113.                 resolve(value);  
  114.             }  
  115.         }).catch(err => {  
  116.             console.log('Error in uploadFileChunk! ' + err);  
  117.             reject(err);  
  118.         });  
  119.     }  
  120.     //Helper method - depending on what chunk of data we are dealing with, we need to use the correct REST method...  
  121.     getUploadMethod(offset, length, total) {  
  122.         if (offset + length + 1 > total) {  
  123.             return 'finishupload';  
  124.         } else if (offset === 0) {  
  125.             return 'startupload';  
  126.         } else if (offset < total) {  
  127.             return 'continueupload';  
  128.         }  
  129.         return null;  
  130.     }  
  131.     //this method slices the blob array buffer to the appropriate chunk and then calls off to get the BinaryString of that chunk  
  132.     convertFileToBlobChunks(result, byteOffset, chunkInfo) {  
  133.         let arrayBuffer = result.slice(chunkInfo.offset, chunkInfo.offset + chunkInfo.length);  
  134.         return this.convertDataBinaryString(arrayBuffer);  
  135.     }  
  136.     guid() {  
  137.         function s4() {  
  138.             return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);  
  139.         }  
  140.         return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();  
  141.     }  
  142. }  

Step4

We should refer the SP.js and SP.RequestExecutor.js in deployed .aspx (or .html) pages to use default SharePoint service request executor to post file.

Output

Finally, the uploaded file will be available in SharePoint Documents Library.

SharePoint

References

  • https://msdn.microsoft.com/en-us/library/office/dn450841.aspx#bk_FileStartUpload
  • https://blogs.technet.microsoft.com/sharepointdevelopersupport/2016/11/23/always-use-file-chunking-to-upload-files-250-mb-to-sharepoint-online/

Summary

In this article, we have explored how to upload a large file in SharePoint online using Angular.