When working with SharePoint Online, you might face challenges when attempting to upload files larger than 2MB using the JavaScript Object Model (JSOM). The default SharePoint Online upload mechanism does not handle large files efficiently. However, using chunking allows you to break up larger files into smaller segments, making the upload process smoother and more reliable.
Understanding the Problem
If you've tried to upload files larger than 2MB directly using JSOM, you've likely encountered errors or unsuccessful uploads. The original code snippet commonly attempted might look like this:
// Sample Code (Original)
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var fileCreationInformation = new SP.FileCreationInformation();
fileCreationInformation.set_overwrite(true);
fileCreationInformation.set_url(file.name);
fileCreationInformation.set_contentStream(new SP.MemoryStream(file));
var uploadFile = web.get_folder('Shared Documents').get_files().add(fileCreationInformation);
clientContext.executeQueryAsync(onSuccess, onFailure);
This snippet attempts to upload a file directly, but for files over 2MB, we need to implement chunking.
Implementing Chunked Uploads
To tackle the issue of uploading files larger than 2MB, we can implement a chunked upload approach. This involves breaking the file into smaller parts and uploading each part sequentially.
Chunking Logic
Here's a step-by-step breakdown of how to upload a file greater than 2MB using JSOM chunking:
- Determine the File Size: Check the file size to see if it exceeds 2MB.
- Set Chunk Size: Define a chunk size, usually set to a smaller value like 1MB.
- Upload Each Chunk: Use a loop to upload each chunk sequentially.
- Finalize the Upload: After all chunks are uploaded, finalize the upload process.
Code Example
Here’s an updated version of the JSOM code to handle chunked uploads:
function uploadFileInChunks(file) {
var chunkSize = 1024 * 1024; // 1MB
var fileSize = file.size;
var start = 0;
var end = Math.min(chunkSize, fileSize);
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var folder = web.get_folder('Shared Documents');
function uploadNextChunk() {
var slice = file.slice(start, end);
var reader = new FileReader();
reader.onload = function (e) {
var arrayBuffer = e.target.result;
var fileCreationInformation = new SP.FileCreationInformation();
fileCreationInformation.set_overwrite(false);
fileCreationInformation.set_url(file.name + "_part_" + start);
fileCreationInformation.set_contentStream(new SP.MemoryStream(arrayBuffer));
var uploadFile = folder.get_files().add(fileCreationInformation);
clientContext.executeQueryAsync(
function () {
start = end;
end = Math.min(start + chunkSize, fileSize);
if (start < fileSize) {
uploadNextChunk();
} else {
console.log('Upload complete!');
}
},
function (sender, args) {
console.error('Upload failed: ' + args.get_message());
}
);
};
reader.readAsArrayBuffer(slice);
}
uploadNextChunk();
}
// Usage
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function () {
var file = fileInput.files[0];
if (file && file.size > 2 * 1024 * 1024) {
uploadFileInChunks(file);
} else {
console.log('File is less than 2MB, using standard upload.');
// You can add the standard upload code here if needed.
}
});
Explanation of the Code
- File Slicing: The code uses the
slice
method to split the file into manageable parts. - FileReader API: This API reads the sliced file segments as
ArrayBuffer
for upload. - Execution of Queries: Each file chunk is uploaded one at a time using the SharePoint JSOM, ensuring that the next chunk begins uploading only after the previous one has finished.
- Error Handling: We add basic error handling to log failed uploads.
Practical Considerations
- Performance: Chunking can significantly reduce the impact of network interruptions. You can also implement retry logic for failed uploads to enhance reliability.
- User Feedback: Consider implementing progress indicators to provide users with feedback on the upload status.
- Browser Compatibility: Always test chunked uploads across different browsers to ensure compatibility.
Useful Resources
By implementing chunking with JSOM in SharePoint Online, you can efficiently upload larger files, enhance user experience, and ensure data reliability during the upload process. Feel free to adapt the provided code to suit your specific requirements!