Upload multiple attachments to SharePoint List Item using REST API jQuery, along with People Picker Column
How to Upload multiple attachments to SharePoint List Item using REST API jQuery, along with People Picker Column
In this post I will show you how we can upload multiple attachments on a SharePoint List item, I am taking a People Picker field here where you can store multiple SharePoint users along with other columns. Please refer the below code, It would be very helpful for you to implement the same in your projects. In the below code you will find how you can clear a input type file and people picker field.
JS Files need to be used -
<!-- SharePoint Specific Javascript Start -->
<!--script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script-->
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/1033/strings.js"></script>
<script type="text/javascript" src="/_layouts/15/clienttemplates.js"></script>
<script type="text/javascript" src="/_layouts/15/clientforms.js"></script>
<script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript" src="/_layouts/15/autofill.js"></script>
<script type="text/javascript"src="_layouts/15/sp.core.js"></script>
<!-- SharePoint Specific Javascript End -->
<script type="text/javascript"src="/js/jquery.MultiFile.js"></script>
<script type="text/javascript" language="javascript">
var versionUpdate = (new Date()).getTime();
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "/js/CAP_Test.js?v=" + versionUpdate;
document.body.appendChild(script);
Code -
var arraycount = 0;
var fileUploadeCount = 0;
$(window).load(function() {
$(".loader").fadeOut("slow");
/*** Initialize ClientSide People Picker ***/
initializePeoplePicker('peoplepicker', true, 'People Only', 44);
//********* Code for Multi-Select File Only Starting *******///////////////
$('#file_input').MultiFile({
max: 5, // Number of Files
maxfile: 5000, // Maximum File Size
//preview:true,
//previewCss:'max-height:100px; max-width:100px;',
list:'#myList'
});
$("#btnSubmitResources").click(function(){
formSave();
});
$("#btnResetResources").click(function(){
$("html").animate({ scrollTop: 0 }, "slow");
clrPeoplePickerAndFields();
});
});
function formSave() {
$(".loader").show();
arraycount = 0;
fileUploadeCount = 0;
var peoplePickerId = 'peoplepicker';
var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerId + '_TopSpan'];
//Get Selected UserInfo From PeoplePicker
var selectedUsers = peoplePicker.GetAllUserInfo();
/*************************************************************************************Get User Id **********************************************************/
//After Selection of peoplePicker Use we will extract each user's email Id. By Using Email Id we will get each user's Userid i.e. Id
//Once we receive id We are going to make an array of Id which will help us to pass user Id i.e. People Picker Column Value
var str ="";
var myObj;
myObj = { "results":[ ]};
for(var a=0;a<selectedUsers.length;a++)
{
/*Get UserEmail Id From Selected Users in People Picket */
var useremail = selectedUsers[a].EntityData.Email;
/*Get User Email Id in Comma Seperated String. This is for reference purpose only */
str += GetUserIDByEmail(useremail) + ",";
/*Get User Id and ADD it into Arrasy so that we can pass this information in Perople Picker Value*/
myObj.results.push(GetUserIDByEmail(useremail));
}
/* Remove Last , (comma) sign from selected userid */
var selectedPeoplePickerID = str.substring(0, str.length-1);
var listItem = "";
var fileArray = [];
$("input:file").each(function () {
if ($(this)[0].files[0]) {
fileArray.push({ "Attachment": $(this)[0].files[0] });
}
});
arraycount = fileArray.length;
listItem = {
__metadata: { "type": "SP.Data.CAP_x005f_ResourcesListItem" },
Title: 'Title',
Region: $("#ddlRegionResources").val(),
Country: $("#ddlCountryResources").val(),
Category: $.unique(CategoryArrResources).join(", "),
ProductType: $.unique(ProductTypeArrResources).join(", "),
CoverageType: CoverageTypeResources,
Reinsurer: $.unique(ReinsurerArrResources).join(", "),
CMO: $("#txtCMO").val(),
TopicCase: $("#txtTopicCase").val(),
Solution: $("#txtSolution").val(),
PresenterId: myObj
//Files: fileArray
};
createNewItem("CAP_Resources", fileArray, listItem);
}
function createNewItem(listname, fileArray, listItem) {
var dfd = $.Deferred();
var initializePermsCall = PostAjax(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listname + "')/items", listItem);
$.when(initializePermsCall).then(function (permData) {
var id = permData.d.Id;
if (fileArray.length != 0) {
for (i = 0; i <= fileArray.length - 1; i++) {
loopFileUpload(listname, id, fileArray, i).then(
function () {
},
function (sender, args) {
console.log("Error uploading");
dfd.reject(sender, args);
}
);
}
}
if (fileArray.length == 0) {
alert("Submiited");
clrPeoplePickerAndFields();
$(".loader").hide();
$("html").animate({ scrollTop: 0 }, "slow");
}
})
.fail(function (sender, args) {
alert('Request failed - ' + sender.responseText);
dfd.reject(sender, args);
console.log(sender, args);
$(".loader").hide();
$("html").animate({ scrollTop: 0 }, "slow");
});
}
function PostAjax(siteurl, listItem) {
return $.ajax({
url: siteurl,
type: "POST",
data: JSON.stringify(listItem),
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
}
});
}
function loopFileUpload(listName, id, fileArray, fileCount) {
var dfd = $.Deferred();
uploadFile(listName, id, fileArray[fileCount].Attachment);
return dfd.promise();
}
function uploadFile(listname, ID, file) {
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();
};
getFileBuffer(file).then(function (buffer) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "')",
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: onAttachmentSucess,
error : onAttachmentErr
});
});
function onAttachmentSucess(data) {
fileUploadeCount++;
if (arraycount == fileUploadeCount) {
console.log(data + ' uploaded successfully');
alert("Submiited");
clrPeoplePickerAndFields();
$(".loader").hide();
$("html").animate({ scrollTop: 0 }, "slow");
}
}
function onAttachmentErr(err) {
alert(JSON.stringify(err));
clrPeoplePickerAndFields();
$(".loader").hide();
}
}
/****************************** Get UserID using Email Code Start **************************************************************************************/
function GetUserIDByEmail(useremail) {
var res ;
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/SiteUsers?$filter=Email%20eq%20%27" + useremail +"%27" ,
async: false,
type: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
//$("#sample").empty();
for (var i = 0; i < data.d.results.length; i++)
{
var item = data.d.results[i];
//$("#sample").append(item.Id + "\t" + item.Title + "<br/>");
res=item.Id;
}
return res;
},
error: function (data) {
failure(data);
}
});
return res;
}
/****************************** Get UserID using Email Code End ***************************************************************************************/
function clrPeoplePickerAndFields(){
$('#ddlRegionResources').val('');
$('#ddlCountryResources').val('');
$('.clr').val('');
$('#myList').html('');
$("#ddlCountryResources").prop("disabled", true);
$('input[name="CategoryResources"]').removeAttr('checked');
$('input[name="Product Type Resources"]').removeAttr('checked');
$('input[name="coverage Resources"]').removeAttr('checked');
$('input[name="Reinsurer Resources"]').removeAttr('checked');
// Resetting File input
var oldInput = document.getElementById("file_input");
var newInput = document.createElement("input");
newInput.type = "file";
newInput.id = oldInput.id;
newInput.name = oldInput.name;
newInput.className = oldInput.className;
newInput.style.cssText = oldInput.style.cssText;
oldInput.parentNode.replaceChild(newInput, oldInput);
$('#file_input').MultiFile({
max: 5, // Number of Files
maxfile: 5000, // Maximum File Size
//preview:true,
//previewCss:'max-height:100px; max-width:100px;',
list:'#myList'
});
// Resetting People Picker
var pickerId = 'peoplepicker';
var toSpanKey = pickerId+"_TopSpan";
var peoplePicker = null;
// Get the people picker object from the page.
var ClientPickerDict = this.SPClientPeoplePicker.SPClientPeoplePickerDict;
// Get the people picker object from the page.
for (var propertyName in ClientPickerDict) {
if (propertyName == toSpanKey) {
peoplePicker = ClientPickerDict[propertyName];
break;
}
}
if (peoplePicker) {
var ResolvedUsersList = $(document.getElementById(peoplePicker.ResolvedListElementId)).find("span[class='sp-peoplepicker-userSpan']");
$(ResolvedUsersList).each(function (index) {
peoplePicker.DeleteProcessedUser(this);
});
}
}
/*** Initialize ClientSide People Picker ***/
function initializePeoplePicker(peoplePickerElementId, AllowMultipleValues, PeopleorGroup, GroupID) {
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
schema['AllowMultipleValues'] = AllowMultipleValues;
if (PeopleorGroup == 'PeopleOnly') schema['PrincipalAccountType'] = 'User';
else schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
if (GroupID > 0) {
schema['SharePointGroupID'] = GroupID
}
// Render and initialize the picker.
// Pass the ID of the DOM element that contains the picker, an array of initial
// PickerEntity objects to set the picker value, and a schema that defines
// picker properties.
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}
Where to Play Blackjack, Slots and Roulette - DRMCD
ReplyDeleteWhere to Play Blackjack, Slots 통영 출장안마 and Roulette – DRMCD The best game 강릉 출장안마 play for Blackjack, Slots and Roulette. Find 시흥 출장안마 a complete list 평택 출장마사지 of all games to play on your 경상남도 출장마사지 mobile device