How I can upload a large file of more than 50mb in sharepoint online using JSOM?

Prashant Agarwal 0 Reputation points
2023-04-24T05:35:10.8533333+00:00
Hi Everyone,
Can you please help me troubleshoot an error that I encountered while uploading a large file using the Chunked Approach in SharePoint? I used the startUpload, continueUpload, and finishUpload methods, but I received the following error message: "parameters.Content, parameters.ContentStream Parameter name: Specified value is not supported for the parameters.Content, parameters.ContentStream parameter."
I have included my code below for reference:

function UploadLargeFile() {

    // Get the context and the SharePoint list where you want to upload the file

    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {

        var context = SP.ClientContext.get_current();

        var hostUrl = "https://slpoc2.sharepoint.com/sites/Dev-HHRES";

        var appContextSite = new SP.AppContextSite(context, hostUrl);

        var docLib = appContextSite.get_web().get_lists().getByTitle('Documents');

        // Set the chunk size to 1 MB

        var chunkSize = 1024 * 1024;

        var fileInput = document.getElementById('fileInput');

        var file = fileInput.files[0];

        debugger

        // Calculate the number of chunks

        var fileSize = file.size;

        var numChunks = Math.ceil(fileSize / chunkSize);

        // Create a new file creation information object

        var fileCreateInfo = new SP.FileCreationInformation();

        fileCreateInfo.set_url(file.name);

        fileCreateInfo.set_overwrite(true);

        sophia papadopoulos

        console.log(fileCreateInfo);

        debugger

        // Upload the file to SharePoint

        var newFile = docLib.get_rootFolder().get_files().add(fileCreateInfo);

        // Upload the file in chunks

        var chunkIndex = 0;

        var offset = 0;

        var chunkReader = new FileReader();

        chunkReader.onload = function (evt) {

            if (evt.target.error == null) {

                var buffer = evt.target.result;

                var endpoint = offset + buffer.byteLength - 1;

                var chunkStream = new SP.Base64EncodedByteArray();

                chunkStream.append(buffer);

                debugger

                // Start uploading the chunk

                if (chunkIndex == 0) {

                

                    var chunkStream = new SP.Base64EncodedByteArray();

                    var uint8Array = new Uint8Array(buffer);

                    chunkStream.append(uint8Array);

                    newFile.startUpload(chunkStream);

                    console.log('Upload start');

                } else {

                    var chunkStream = new SP.Base64EncodedByteArray();

                    chunkStream.append(buffer);

                    newFile.continueUpload(chunkStream);

                    console.log('upload continuously');

                //    newFile.continueUpload(chunkStream);

                //    console.log('upload continuously');

                }

                

                // If this is the last chunk, finish the upload

                if (chunkIndex == numChunks - 1) {

                    console.log('finish the work');

                         debugger

                    newFile.finishUpload();

                    context.executeQueryAsync(function () {

                        // File uploaded successfully

                        console.log('File uploaded successfully!');

                    }, function (sender, args) {

                        // Error uploading file

                        console.log(sender);

                        console.log(args);

                        console.log(args.get_message());

                    });

                } else {

                    // Upload the next chunk

                    offset += buffer.byteLength;

                    chunkIndex++;

                    readNextChunk();

                }

            }

        };

        var readNextChunk = function () {

            var start = offset;

            var end = Math.min(start + chunkSize, fileSize);

            chunkReader.readAsArrayBuffer(file.slice(start, end));

        };

        readNextChunk();

    });

    

}
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
10,682 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 35,466 Reputation points Microsoft Vendor
    2023-04-24T08:54:41.9733333+00:00

    Hi @Prashant Agarwal, You can refer to following code to upload file

    function uploadmultifiles(){
    var fileCountCheck = 0;
    var listName="TargetListName";
    var id = 12; //you can pass the ID dynamically
    console.error("before if",fileCountCheck);
    //fileObj ---->>> array of files
       if (fileObj.length != 0) {
        console.error("after if",fileObj.length);
        console.error(fileCountCheck <= fileObj.length - 1);
            if (fileCountCheck <= fileObj.length - 1) {
                console.error("before loopFileUpload",fileObj);
                loopFileUpload(listName, id, fileObj, fileCountCheck).then(
            function () {
            },
            function (sender, args) {
                console.error("Error uploading");
                dfd.reject(sender, args);
            }
            );
        }
     }
     else {
        deferred.resolve(fileCountCheck);
     }
    }
    
    function loopFileUpload(listName, id, listValues, fileCountCheck) {
    var dfd = $.Deferred();
    console.error("loopFileUpload",listValues[fileCountCheck]);
    console.error("getattachmet",listValues[fileCountCheck]);
    
    uploadFile(listName, id, listValues[fileCountCheck]).then(
        function (data) {                      
            var objcontext = new SP.ClientContext();
            var targetList = objcontext.get_web().get_lists().getByTitle(listName);
            var listItem = targetList.getItemById(id);
            objcontext.load(listItem);
            objcontext.executeQueryAsync(function () {
                console.error("Reload List Item- Success");                                      
                fileCountCheck++;
                if (fileCountCheck <= listValues.length - 1) {
                    loopFileUpload(listName, id, listValues, fileCountCheck);
                } else {
                    console.error(fileCountCheck + ": Files uploaded");
                }
            },
            function (sender, args) {
                console.error("Reload List Item- Fail" + args.get_message());
            });                  
    
        },
        function (sender, args) {
            console.error("Not uploaded");
            dfd.reject(sender, args);
        }
    );
    return dfd.promise();
    }
    
    function uploadFile(listName, id, file) {
    var deferred = $.Deferred();
    console.error("get file object", file);
    if(file.name != window.undefined)
    {
    var fileName = file.name;console.error(fileName);
    console.error("filename", fileName);
    getFileBuffer(file).then(
        function (buffer) {
            var bytes = new Uint8Array(buffer);
            var binary = '';
            for (var b = 0; b < bytes.length; b++) {
                binary += String.fromCharCode(bytes[b]);
            }
            var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
            console.error(' File size:' + bytes.length);
            $.getScript(scriptbase + "SP.RequestExecutor.js", function () {
                var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);
                createitem.executeAsync({
                    url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + fileName + "')",
                    method: "POST",
                    binaryStringRequestBody: true,
                    body: binary,
                    success: fsucc,
                    error: ferr,
                    state: "Update"
                });
                function fsucc(data) {
                    console.error(data + ' uploaded successfully');
                    deferred.resolve(data);
                }
                function ferr(data) {
                    console.error(fileName + "not uploaded error");
                    deferred.reject(data);
                }
            });
    
        },
        function (err) {
            deferred.reject(err);
        }
    );
    }
    else
        deferred.resolve("");
    return deferred.promise();
    }
    
    function getFileBuffer(file) {
    var deferred = $.Deferred();
    var reader = new FileReader();
    reader.onload = function (e) {
        deferred.resolve(e.target.result);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(file);
    return deferred.promise();
    }
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.