3

Can someone suggest me a way to upload multiple files to SharePoint List item using JSOM? I can upload a single file to the list item. But i m unable to upload multiple files to list item at one time.

Selva
  • 51
  • 3
  • 9
  • What version of SharePoint are you using? And do you mean uploading to a document library or attaching a file to a list item? – Robin Aug 24 '17 at 19:11
  • Hi I m using O365 SharePoint 2013 online version. This is a custom SharePoint list. – Selva Aug 25 '17 at 14:02

2 Answers2

2

You can find the complete code here. It worked well.

http://techfindings-prem.blogspot.com/2014/11/uploading-multiple-attachments-to-lists.html

Here is the code

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();
}

Updated:- You need ensure you are passing array of file objects in fileObj variable as shown below.

enter image description here

Br,
Srini K

Srini K
  • 429
  • 1
  • 5
  • 16
  • Have you tried this one. I tried this once. This does not seems to be working. – Selva Aug 24 '17 at 19:54
  • Yes i tried this one. Working. What error are you getting ? Can you post the error here? – Srini K Aug 24 '17 at 19:59
  • When i implemented this code in my page using JSOM (after adding the multiple.js files), the page did not render. however, no errors were listed. If possible can you send me your correct code snippet to my email id: sreuben2006@aol.com – Selva Aug 24 '17 at 20:49
  • Update above with code. Please check. – Srini K Aug 24 '17 at 21:30
  • Srini, Thanks for the Code snippet. I forgot to add one more point here. I m using O365 SharePoint 2013. Can i still implement this one with my jquery? – Selva Aug 25 '17 at 13:58
  • Yes, you can. It will work on both version. – Srini K Aug 25 '17 at 22:06
  • Srini, i m getting file.name as undefined. It says file uploaded. but the attachment is not uploaded. i m using the following file attachment html.
    – Selva Aug 28 '17 at 21:37
  • I have updated answer above. You need to ensure you are passing array of file objects in fileObj variable. Hopefully you can finish now..!! – Srini K Aug 29 '17 at 02:51
  • Srini, can you let me know how to attach each file item to the array object. If not, can it be done by having more than 1 file upload control. – Selva Aug 29 '17 at 21:58
  • Yes you do by multiple file upload controls in a for loop, etc., Array I mentioned is for iterating multiple items. – Srini K Sep 03 '17 at 04:22
0

The below code (file upload through REST API) can be used to upload multiple files to list item attachment.

First we are creating the new item in the list and then attaching the files.

var getFileBuffer = function(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();

};

var payload = { __metadata: { type: "SP.Data.<<LIST_NAME>>ListItem" }, 'Title': "NEW TITLE" };

$.ajax( { url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('<<LIST_NAME>>')/items", type: "POST", data: JSON.stringify(payload), headers: { "Accept": "application/json;odata=verbose", "Content-Type": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), "X-HTTP-Method": "POST" }, success: function(data, status, xhr) { var itemID = data.d.ID;

    var fileArray = document.getElementById(&quot;file_input&quot;).files; // &lt;input type=&quot;file&quot; class=&quot;form-control-file&quot; id=&quot;file_input&quot; multiple&gt;
    var arraycount = fileArray.length;
    var fileUploadedCount = 0;
    var curFileName = [];

    for (var i = 0; i &lt; arraycount; i++)
    {
        curFileName[i] = fileArray[i].name;
        getFileBuffer(fileArray[i]).then(function(buffer)
        {
            debugger;
            $.ajax(
            {
                url: _spPageContextInfo.webAbsoluteUrl + &quot;/_api/web/lists/getbytitle('&lt;&lt;LIST_NAME&gt;&gt;')/items(&quot; + itemID + &quot;)/AttachmentFiles/add(FileName='&quot; + curFileName[fileUploadedCount] + &quot;')&quot;,
                method: 'POST',
                async: false,
                data: buffer,
                processData: false,
                headers:
                {
                    &quot;Accept&quot;: &quot;application/json; odata=verbose&quot;,
                    &quot;content-type&quot;: &quot;application/json; odata=verbose&quot;,
                    &quot;X-RequestDigest&quot;: document.getElementById(&quot;__REQUESTDIGEST&quot;).value
                },
                success: function()
                {
                    fileUploadedCount++;
                    if (arraycount == fileUploadedCount)
                    {
                        console.log('uploaded successfully');
                    }
                }
            });
        });
    }
},
error: function(xhr, status, error)
{
    console.log(error);
}

});

Jefin Mathew
  • 403
  • 5
  • 16