Introduction

This article will help you upload the large files in the SharePoint online library into smaller chunks. This article is based on the article, Programmatically Uploading Large Files In SharePoint Online, with some enhancement.
It will walk through step-by-step how to upload the file in SharePoint Online.
Step 1
Create a library in Sharepoint online, eg. Name it Test_ABC.
Step 2
Install Node.js from here
Step 3
Create an Angular project(LargeFileUpload) using AngularCLI
Step 4
Create a proxy setting for Angular with Sharepoint online using my blog Proxy With Angular 6+ And SharePoint Environment.
Step 5
Create a FileUpload Component using the below Command
  1. ng g c FileUpload
Step 6
Create a FileUpload and GlobalServices services using the following commandL
  1. ng g s services/FileUpload
  2. ng g s services/GlobalService
GlobalServices.ts
  1. export class GlobalServiceService {
  2. constructor() { }
  3. public sharePointPageObject = {
  4. webAbsoluteUrl: '',
  5. webRelativeUrl : '',
  6. userId: 0
  7. };
  8. }
app.component.ts
  1. import { Component } from '@angular/core';
  2. import { GlobalServiceService } from './services/global-service.service';
  3. declare const _spPageContextInfo;
  4. @Component({
  5. selector: 'app-root',
  6. templateUrl: './app.component.html',
  7. styleUrls: ['./app.component.css']
  8. })
  9. export class AppComponent {
  10. constructor(
  11. private globalService: GlobalServiceService
  12. ) { }
  13. ngOnInit() {
  14. this.globalService.sharePointPageObject.webAbsoluteUrl = window.location.href.indexOf('localhost') > -1 ? '/Your sitecollection'
  15. : _spPageContextInfo.webAbsoluteUrl;
  16. this.globalService.sharePointPageObject.webRelativeUrl = window.location.href.indexOf('localhost') > -1 ? '/Your sitecollection'
  17. : _spPageContextInfo.webRelativeUrl;
  18. this.globalService.sharePointPageObject.userId = window.location.href.indexOf('localhost') > -1 ? 22 : _spPageContextInfo.userId;
  19. }
  20. }
Once the template for file upload is created, then update the file-upload.component.html
  1. File Upload: <input placeholder="Upload File" type="file" (change)="largeFileUpload($event)">
Then file-upload.component.ts as:
  1. import { Component, OnInit } from '@angular/core';
  2. import { FileUploadService } from '../services/file-upload.service';
  3. @Component({
  4. selector: 'app-file-upload',
  5. templateUrl: './file-upload.component.html',
  6. styleUrls: ['./file-upload.component.css']
  7. })
  8. export class FileUploadComponent implements OnInit {
  9. constructor(
  10. private fileUploadService: FileUploadService
  11. ) { }
  12. ngOnInit() {
  13. }
  14. largeFileUpload(event: any) {
  15. let fileList: FileList = event.target.files;
  16. if (fileList.length != 0) {
  17. this.fileUploadService.fileUpload(fileList[0], "Test_ABC", fileList[0].name).then(addFileToFolder => {
  18. console.log("Large File Uploaded Successfully");
  19. }).catch(error => {
  20. console.log("Error while uploading" + error);
  21. });
  22. }
  23. }
  24. }
file-upload.services.ts
  1. import { Injectable } from '@angular/core';
  2. import { GlobalServiceService } from './global-service.service';
  3. import { HttpClient, HttpErrorResponse } from '@angular/common/http';
  4. declare const $: any;
  5. @Injectable({
  6. providedIn: 'root'
  7. })
  8. export class FileUploadService {
  9. constructor(
  10. private globalService: GlobalServiceService,
  11. private httpClient: HttpClient
  12. ) { }
  13. public siteUrl: string = this.globalService.sharePointPageObject.webAbsoluteUrl;
  14. public siteRelativeUrl: string = this.globalService.sharePointPageObject.webAbsoluteUrl != "/" ? this.globalService.sharePointPageObject.webAbsoluteUrl : "";
  15. public fileUpload(file: any, documentLibrary: string, fileName: string) {
  16. return new Promise((resolve, reject) => {
  17. this.createDummyFile(fileName, documentLibrary).then(result => {
  18. let fr = new FileReader();
  19. let offset = 0;
  20. // the total file size in bytes...
  21. let total = file.size;
  22. // 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)...
  23. let length = 1000000 > total ? Math.round(total * 0.8) : 1000000
  24. let chunks = [];
  25. //reads in the file using the fileReader HTML5 API (as an ArrayBuffer) - readAsBinaryString is not available in IE!
  26. fr.readAsArrayBuffer(file);
  27. fr.onload = (evt: any) => {
  28. while (offset < total) {
  29. //if we are dealing with the final chunk, we need to know...
  30. if (offset + length > total) {
  31. length = total - offset;
  32. }
  33. //work out the chunks that need to be processed and the associated REST method (start, continue or finish)
  34. chunks.push({
  35. offset,
  36. length,
  37. method: this.getUploadMethod(offset, length, total)
  38. });
  39. offset += length;
  40. }
  41. //each chunk is worth a percentage of the total size of the file...
  42. const chunkPercentage = (total / chunks.length) / total * 100;
  43. console.log("Chunk Percentage: "+chunkPercentage);
  44. if (chunks.length > 0) {
  45. //the unique guid identifier to be used throughout the upload session
  46. const id = this.generateGUID();
  47. //Start the upload - send the data to S
  48. this.uploadFile(evt.target.result, id, documentLibrary, fileName, chunks, 0, 0, chunkPercentage, resolve, reject);
  49. }
  50. };
  51. })
  52. });
  53. }
  54. createDummyFile(fileName, libraryName) {
  55. return new Promise((resolve, reject) => {
  56. // Construct the endpoint - The GetList method is available for SharePoint Online only.
  57. var serverRelativeUrlToFolder = "decodedurl='" + this.siteRelativeUrl + "/" + libraryName + "'";
  58. var endpoint = this.siteUrl + "/_api/Web/GetFolderByServerRelativePath(" + serverRelativeUrlToFolder + ")/files" + "/add(overwrite=true, url='" + fileName + "')"
  59. const headers = {
  60. "accept": "application/json;odata=verbose"
  61. };
  62. this.executePost(endpoint, this.convertDataBinaryString(2), headers).then(file => resolve(true)).catch(err => reject(err));
  63. });
  64. }
  65. // Base64 - this method converts the blob arrayBuffer into a binary string to send in the REST request
  66. convertDataBinaryString(data) {
  67. let fileData = '';
  68. let byteArray = new Uint8Array(data);
  69. for (var i = 0; i < byteArray.byteLength; i++) {
  70. fileData += String.fromCharCode(byteArray[i]);
  71. }
  72. return fileData;
  73. }
  74. //this method sets up the REST request and then sends the chunk of file along with the unique indentifier (uploadId)
  75. uploadFileChunk(id, libraryPath, fileName, chunk, data, byteOffset) {
  76. return new Promise((resolve, reject) => {
  77. let offset = chunk.offset === 0 ? '' : ',fileOffset=' + chunk.offset;
  78. //parameterising the components of this endpoint avoids the max url length problem in SP (Querystring parameters are not included in this length)
  79. let endpoint = this.siteUrl + "/_api/web/getfilebyserverrelativeurl('" + this.siteRelativeUrl + "/" + libraryPath + "/" + fileName + "')/" + chunk.method + "(uploadId=guid'" + id + "'" + offset + ")";
  80. const headers = {
  81. "Accept": "application/json; odata=verbose",
  82. "Content-Type": "application/octet-stream"
  83. };
  84. this.executePost(endpoint, data, headers).then(offset => resolve(offset)).catch(err => reject(err));
  85. });
  86. }
  87. //the primary method that resursively calls to get the chunks and upload them to the library (to make the complete file)
  88. uploadFile(result, id, libraryPath, fileName, chunks, index, byteOffset, chunkPercentage, resolve, reject) {
  89. //we slice the file blob into the chunk we need to send in this request (byteOffset tells us the start position)
  90. const data = this.convertFileToBlobChunks(result, chunks[index]);
  91. //upload the chunk to the server using REST, using the unique upload guid as the identifier
  92. this.uploadFileChunk(id, libraryPath, fileName, chunks[index], data, byteOffset).then(value => {
  93. const isFinished = index === chunks.length - 1;
  94. index += 1;
  95. const percentageComplete = isFinished ? 100 : Math.round((index * chunkPercentage));
  96. console.log("Percentage Completed:" +percentageComplete)
  97. //More chunks to process before the file is finished, continue
  98. if (index < chunks.length) {
  99. this.uploadFile(result, id, libraryPath, fileName, chunks, index, byteOffset, chunkPercentage, resolve, reject);
  100. } else {
  101. resolve(value);
  102. }
  103. }).catch(err => {
  104. console.log('Error in uploadFileChunk! ' + err);
  105. reject(err);
  106. });
  107. }
  108. //Helper method - depending on what chunk of data we are dealing with, we need to use the correct REST method...
  109. getUploadMethod(offset, length, total) {
  110. if (offset + length + 1 > total) {
  111. return 'finishupload';
  112. } else if (offset === 0) {
  113. return 'startupload';
  114. } else if (offset < total) {
  115. return 'continueupload';
  116. }
  117. return null;
  118. }
  119. //this method slices the blob array buffer to the appropriate chunk and then calls off to get the BinaryString of that chunk
  120. convertFileToBlobChunks(result, chunkInfo) {
  121. return result.slice(chunkInfo.offset, chunkInfo.offset + chunkInfo.length);
  122. }
  123. generateGUID() {
  124. function s4() {
  125. return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  126. }
  127. return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
  128. }
  129. async executePost(url, data, requestHeaders) {
  130. const res = await this.httpClient.post(url, data, requestHeaders).toPromise().catch((err: HttpErrorResponse) => {
  131. const error = err.error;
  132. return error;
  133. });
  134. return this.parseRetSingle(res);
  135. }
  136. parseRetSingle(res) {
  137. if (res) {
  138. if (res.hasOwnProperty('d')) {
  139. return res.d;
  140. } else if (res.hasOwnProperty('error')) {
  141. const obj: any = res.error;
  142. obj.hasError = true;
  143. return obj;
  144. } else {
  145. return {
  146. hasError: true,
  147. comments: res
  148. };
  149. }
  150. } else {
  151. return {
  152. hasError: true,
  153. comments: 'Check the response in network trace'
  154. };
  155. }
  156. }
  157. }
Finally, run the code using the command:
  1. npm run start
Now, your requests will be served at http://localhost:4200/.
Click on browse and select the file for upload.
Once the project runs successfully, the library looks like:
Download the full source code from the attachment.