Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Starting the large file upload using chunks
//Helper method - depending on what chunk of data we are dealing with, we need to use the correct REST method...
function getUploadMethod(offset, length, total) {
if (offset + length + 1 > total) {
return 'finishupload';
} else if (offset === 0) {
return 'startupload';
} else if (offset < total) {
return 'continueupload';
}
return null;
}
module.exports = {
upload: (file) => {
return new Promise((resolve, reject) => {
let ctx = jsomAppContext();
//we have already done this bit...
createDummaryFile(ctx, file.name, 'Documents').then(result => {
let fr = new FileReader();
let offset = 0;
// the total file size in bytes...
let total = file.size;
// 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)...
let length = 1000000 > total ? total * 0.8 : 1000000;
let chunks = [];
fr.onload = evt => {
while (offset < total) {
//if we are dealing with the final chunk, we need to know...
if (offset + length > total) {
length = total - offset;
}
//work out the chunks that need to be processed and the associated REST method (start, continue or finish)
chunks.push({ offset, length, method: getUploadMethod(offset, length, total) });
offset += length;
}
//each chunk is worth a percentage of the total size of the file...
const chunkPercentage = parseFloat(((total / chunks.length) / total)) * 100;
if (chunks.length > 0) {
//the unique guid identifier to be used throughout the upload session
const id = utils.getGuid();
//Start the upload - send the data to SP (we will show the uploadFile function in the next step)...
uploadFile(evt.target.result, id, 'Documents', file.name, chunks, 0, 0, chunkPercentage, resolve, reject);
}
};
//reads in the file using the fileReader HTML5 API (as an ArrayBuffer) - readAsBinaryString is not available in IE!
fr.readAsArrayBuffer(file);
});
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment