Uploading Attachment To The New Item On List Using “REST API” jQuery

Introduction

In the previous article, we have explored multiple attachments to the new item on a list using JSOM and REST API. In this article, we will see how we can upload the documents to SharePoint list items using REST API based approach.

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 will create a new item and that item ID, we have attached in the 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 is highlighted to facilitate multi-file upload control. I am leveraging "jquery.multifile.js" plugin. If we don't use that plugin, the user will be able to select only one input file for upload only one file at a time.

  1.     <script type="text/javascript" src="/Script/jquery-1.10.2.js"></script>  
  2.     <script type="text/javascript" src="/Script/jquery-ui.js"></script>  
  3.     <script type="text/javascript" src="/_layouts/15/sp.js"></script>  
  4.     <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>  
  5.  <script type="text/javascript" src="/Script/jquery.multifile.js"></script>  
  6.   
  7.   <span style="font-size: 22.0pt;padding-left:20px">Personal Details<o:p></o:p></span>  
  8. <table align="left" border="1" cellpadding="0" cellspacing="0" class="MsoTableGrid" width="0" id="mytable">  
  9.         <tbody>  
  10.             <tr>  
  11.                 <td >  
  12.                     <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>  
  13.    <td valign="top" style="padding:9px;" class="auto-style17">  
  14.                                     <input type="text" value="" maxlength="255" id="Name" title="Name" style="width: 96%;" class="ms-long ms-spellcheck-true">  
  15.                                 </td></tr><tr >  
  16.                                 <td class="auto-style16"><h3> Address</h3>                           </td><td class="auto-style17">  
  17.                                     <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>  
  18.  <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 >  
  19. Contact Number </h3></td>  
  20. <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>  
  21. <tr ><td ><span style="font-family: " segoe ui" ,sans-serif; color: #444444">Click here to attach file</span> <div class="files" id="attachFilesHolder ">  
  22.   <input id="file_input" type="file" name="files[]">  
  23.                                     </div>  
  24. </td><td></td></tr></tbody></table>  
  25.                    <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>  
  26.         </tbody></table>  

SharePoint

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.

  1. <script type="text/javascript">  
  2.     var arraycount = 0;  
  3.     var fileUploadeCount = 0;  
  4.   
  5.     $(document).ready(function ($) {  
  6.   
  7.         $('#file_input').multifile();  
  8.   
  9.         $("#NewSaveItem").click(function () { formSave() });  
  10.   
  11.   
  12.     });  
  13.     function formSave() {  
  14.         var listItem = "";  
  15.         var fileArray = [];  
  16.         $("#attachFilesHolder input:file").each(function () {  
  17.             if ($(this)[0].files[0]) {  
  18.                 fileArray.push({ "Attachment": $(this)[0].files[0] });  
  19.             }  
  20.         });  
  21.         arraycount = fileArray.length;  
  22.         listItem = {  
  23.             __metadata: { "type""SP.Data.BankDetailsListItem" },  
  24.             "Name": $("input[title='Name']").val(),  
  25.             "Address ": $("input[title='Address']").val(),  
  26.             "City": $("input[title= City]").val(),  
  27.             "ContactNumber": $("input[title='ContactNumber']").val(),  
  28.             "Files": fileArray  
  29.         };  
  30.         createItemparent("BankDetails", filesarray, listItem);  
  31.     }  
  32.     function createNewItem(listname, filearray, listItem) {  
  33.         var dfd = $.Deferred();  
  34.         var initializePermsCall = PostAjax(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listname + "')/items", listItem);  
  35.         $.when(initializePermsCall).then(function (permData) {  
  36.             var id = permData.d.Id;  
  37.             if (filearray.length != 0) {  
  38.                 for (i = 0; i <= filearray.length - 1; i++) {  
  39.   
  40.                     loopFileUpload(listname, id, filearray, i).then(  
  41.                         function () {  
  42.                         },  
  43.                         function (sender, args) {  
  44.                             console.log("Error uploading");  
  45.                             dfd.reject(sender, args);  
  46.                         }  
  47.                     );  
  48.                 }  
  49.             }  
  50.         });  
  51.     }  
  52.     function PostAjax(siteurl, listItem) {  
  53.         return $.ajax({  
  54.             url: siteurl,  
  55.             type: "POST",  
  56.             contentType: "application/json;odata=verbose",  
  57.             data: JSON.stringify(listItem),  
  58.             headers: {  
  59.                 "Accept""application/json;odata=verbose",  
  60.                 "X-RequestDigest": $("#__REQUESTDIGEST").val()  
  61.             }  
  62.         });  
  63.     }  
  64.     function loopFileUpload(listName, id, filearray, fileCount) {  
  65.         var dfd = $.Deferred();  
  66.         uploadFile(listName, id, filearray[fileCount].Attachment); return dfd.promise();  
  67.     }  
  68.     function uploadFile(listname, ID, file) {  
  69.         var getFileBuffer = function (file) {  
  70.   
  71.             var deferred = $.Deferred();  
  72.             var reader = new FileReader();  
  73.   
  74.             reader.onload = function (e) {  
  75.                 deferred.resolve(e.target.result);  
  76.             }  
  77.             reader.onerror = function (e) {  
  78.                 deferred.reject(e.target.error);  
  79.             }  
  80.             reader.readAsArrayBuffer(file);  
  81.             return deferred.promise();  
  82.         };  
  83.   
  84.         getFileBuffer(file).then(function (buffer) {  
  85.             $.ajax({  
  86.                 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "')",  
  87.                 method: 'POST',  
  88.                 async: false,  
  89.                 data: buffer,  
  90.                 processData: false,  
  91.                 headers: {  
  92.                     "Accept""application/json; odata=verbose",  
  93.                     "content-type""application/json; odata=verbose",  
  94.                     "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value  
  95.   
  96.                 }, success: onAttachmentSucess  
  97.   
  98.             });  
  99.   
  100.         });  
  101.         function onAttachmentSucess() {  
  102.             fileUploadeCount++;  
  103.             if (arraycount == fileUploadeCount) {  
  104.                 console.log(data + ' uploaded successfully');  
  105.             }  
  106.         }  
  107.     }  
  108. /script>  

Final O/P

Final O/P

Up Next
    Ebook Download
    View all
    Learn
    View all