Upload attachment to new item on list using REST API JQuery in SharePoint 2013

sharepoint 2013 rest api attach file to list item
InfoPath alternatives for form designing SharePoint

Introduction:
Here in this SharePoint article we will discuss how we can upload attachment to new item in SharePoint list using Rest API and jQuery in SharePoint 2013. In my previous post we have discussed on multiple attachments to the new item on list using JSOM and REST API.

So far I have seen everyone blogging and posting articles, where they follow the approach of hardcoding the item ID and passing it to REST API and Uploading. But In this article we create new item that item ID we attached attachment.

Check the step by step guide below:

Steps:

The below code snippet will show the Personal Details html that has been created for the user to insert data into the list. In Html One tag highlighted to facilitate multi file upload control, I am leveraging “jquery.multifile.js” plugin. If we don’t use that plugin, the user will select only one input file for upload



<script type=”text/javascript” src=”/Script/jquery-1.10.2.js”></script>

<script type=”text/javascript” src=”/Script/jquery-ui.js”></script>

<script type=”text/javascript” src=”/_layouts/15/sp.js”></script>

<script type=”text/javascript” src=”/_layouts/15/sp.runtime.js”></script>

<script type=”text/javascript” src=”/Script/jquery.multifile.js”></script>

<span style=”font-size: 22.0pt; padding-left: 20px”>Personal Details<o:p></o:p></span>

<table align=”left” border=”1″ cellpadding=”0″ cellspacing=”0″ class=”MsoTableGrid” width=”0″ id=”mytable”>

<tbody>

<tr>

<td>

<table align=”left” border=”1″ cellpadding=”0″ cellspacing=”0″ class=”MsoTableGrid” style=””>

<tbody>

<tr>

<td style=”” valign=”top” class=”auto-style16″>

<h3>Name</h3>

</td>

<td valign=”top” style=”padding: 9px;” class=”auto-style17″>

<input type=”text” value=”” maxlength=”255″ id=”Name” title=”Name” style=”width: 96%;” class=”ms-long ms-spellcheck-true”>

</td>

</tr>

<tr>

<td class=”auto-style16″>

<h3>Address</h3>

</td>

<td class=”auto-style17″>

<input type=”text” value=”” maxlength=”255″ id=” Address” title=”Address” style=”ime-mode: ; width: 96%;” class=”ms-long ms-spellcheck-true”></td>

</tr>

<tr>

<td class=”auto-style15″>

<h3>City</h3>

</td>

<td class=”auto-style4″>

<input type=”text” value=”” maxlength=”255″ id=” City ” title=” City ” style=”width: 96%;” class=”ms-long ms-spellcheck-true”></td>

</tr>

<tr>

<td class=”auto-style15″>

<h3>Contact Number </h3>

</td>

<td class=”auto-style5″>

<input type=”text” value=”” maxlength=”255″ id=” ContactNumber ” title=”ContactNumber” style=”ime-mode: ; width: 96%;” class=”ms-long ms-spellcheck-true”></td>

</tr>

</tbody>

</table>

<table>

<tbody>

<tr>

<td><span style=”font-family: &quot; segoe ui&quot; ,sans-serif; color: #444444″>Click here to attach file</span>

<div class=”files” id=”attachFilesHolder “>

<input id=”file_input” type=”file” name=”files[]”>

</div>

</td>

<td></td>

</tr>

</tbody>

</table>

<div style=”text-align: -webkit-center; padding-bottom: 20px; padding-top: 20px; padding-left: 190px”>

<input name=”SaveItem” style=”height: 40px; font-size: 15px;” class=”ms-ButtonHeightWidth” id=” NewSaveItem ” accesskey=”O” onclick=”” type=”button” value=”Click here to submit ” target=”_self”>

</div>

</tbody>

</table>

sharepoint 2013 rest api attach file to list item
sharepoint 2013 rest api attach file to list item

Also check some SharePoint online Rest API articles:
– Different operations on SharePoint 2013 people picker

– Calling SharePoint Search Using REST from JavaScript

– SharePoint 2013 Hide or Show Delete Icon In Ribbon On List Item Selection using jQuery

Step-1:
Navigate to your SharePoint 2013 site.

Step-2:
From this page, select Site Actions | Edit Page.

Edit the page, go to the Insert tab in the Ribbon and click Web Part option. In Web Parts picker area, go to the Media and Content category, select the Script Editor Web Part and press the Add button.

Step-3:
Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert HTML and/or JavaScript, as shown below.

<script type=”text/javascript”>

var arraycount = 0;

var fileUploadeCount = 0;

$(document).ready(function ($) {

$(‘#file_input’).multifile();

$(“#NewSaveItem”).click(function () { formSave() });

});

function formSave() {

var listItem = “”;

var fileArray = [];

$(“#attachFilesHolder input:file”).each(function () {

if ($(this)[0].files[0]) {

fileArray.push({ “Attachment”: $(this)[0].files[0] });

}

});

arraycount = fileArray.length;

listItem = {

__metadata: { “type”: “SP.Data.BankDetailsListItem” },

“Name”: $(“input[title=’Name’]”).val(),

“Address “: $(“input[title=’Address’]”).val(),

“City”: $(“input[title= City]”).val(),

“ContactNumber”: $(“input[title=’ContactNumber’]”).val(),

“Files”: fileArray

};

createItemparent(“BankDetails”, filesarray, 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);

}

);

}

}

});

}

function PostAjax(siteurl, listItem) {

return $.ajax({

url: siteurl,

type: “POST”,

contentType: “application/json;odata=verbose”,

data: JSON.stringify(listItem),

headers: {

“Accept”: “application/json;odata=verbose”,

“X-RequestDigest”: $(“#__REQUESTDIGEST”).val()

}

});

}

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

});

});

function onAttachmentSucess() {

fileUploadeCount++;

if (arraycount == fileUploadeCount) {

console.log(data + ‘ uploaded successfully’);

}

}

}

</script>

Final Output:

upload attachment using rest api sharepoint online
upload attachment using rest api sharepoint online

Hope this will be helpful.

Similar SharePoint 2013 Tutorials


About Sagar Pardeshi

I am Developer working on Microsoft Technologies for the past 6+years. I am very much passionate about programming and my core skills are SharePoint, ASP.NET & C#,Jquery,Javascript,REST. I am running this blog to share my experience & learning with the community I am an MCP, MCTS .NET & Sharepoint 2010, MCPD Sharepoint 2010, and MCSD HTML 5,Sharepoint 2013 Core Solutions. I am currently working on Sharepoint 2010, MOSS 2007, Sharepoint 2013,Sharepoint 2013 App Dev, C#, ASP.NET, and SQL Server 2008.

View all posts by Sagar Pardeshi →

Leave a Reply