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.
-
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– Robin2017-08-24 19:11:07 +00:00Commented Aug 24, 2017 at 19:11
-
Hi I m using O365 SharePoint 2013 online version. This is a custom SharePoint list.Selva– Selva2017-08-25 14:02:17 +00:00Commented Aug 25, 2017 at 14:02
2 Answers
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.
Br,
Srini K
-
Have you tried this one. I tried this once. This does not seems to be working.Selva– Selva2017-08-24 19:54:22 +00:00Commented Aug 24, 2017 at 19:54
-
Yes i tried this one. Working. What error are you getting ? Can you post the error here?Srini K– Srini K2017-08-24 19:59:06 +00:00Commented Aug 24, 2017 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: [email protected]Selva– Selva2017-08-24 20:49:40 +00:00Commented Aug 24, 2017 at 20:49
-
Update above with code. Please check.Srini K– Srini K2017-08-24 21:30:41 +00:00Commented Aug 24, 2017 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– Selva2017-08-25 13:58:20 +00:00Commented Aug 25, 2017 at 13:58
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("file_input").files; // <input type="file" class="form-control-file" id="file_input" multiple>
var arraycount = fileArray.length;
var fileUploadedCount = 0;
var curFileName = [];
for (var i = 0; i < arraycount; i++)
{
curFileName[i] = fileArray[i].name;
getFileBuffer(fileArray[i]).then(function(buffer)
{
debugger;
$.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('<<LIST_NAME>>')/items(" + itemID + ")/AttachmentFiles/add(FileName='" + curFileName[fileUploadedCount] + "')",
method: 'POST',
async: false,
data: buffer,
processData: false,
headers:
{
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
},
success: function()
{
fileUploadedCount++;
if (arraycount == fileUploadedCount)
{
console.log('uploaded successfully');
}
}
});
});
}
},
error: function(xhr, status, error)
{
console.log(error);
}
});
