SharePoint 2013 - Uploading Multiple Attachments To The New Item On List Using JSOM And REST API

Introduction

In this article, we will explore how we can attach multiple attachments to the new item on list using JSOM and REST API.

There are dozens of blog posts and articles out there about uploading files to SharePoint, and some of them even mention attachments. But I found that not a single one of the articles provide a step by step guide to create new item and attachments to itself.

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 I have come up with another way of implementing the same. 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 -ile 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.

  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 oLoader;  
  3.     var attcount = 0;  
  4.     var arraycount = 0;  
  5.         $(document).ready(function ($) {  
  6.            $('#file_input').multifile();//For facilitate multi file upload  
  7.   
  8.         $("#NewSaveItem").click(function () { formSave() });  
  9.   
  10.     });  
  11.   
  12.   
  13.     function formSave() {  
  14.             oLoader = SP.UI.ModalDialog.showWaitScreenWithNoClose("Working on it""Creating New Bank Account...");  
  15.             for (i = 0; i < count; i++) {  
  16.   
  17.                 var data = [];  
  18.                 var fileArray = [];  
  19.                 $("#attachFilesHolder input:file").each(function () {  
  20.                     if ($(this)[0].files[0]) {  
  21.                         fileArray.push({ "Attachment": $(this)[0].files[0] });  
  22.                     }  
  23.                 });  
  24.                 data.push({  
  25.                     "Name": $("input[title='Name']").val(),  
  26.                     " Address ": $("input[title='Address']").val(),  
  27.                     "City": $("input[title= City]").val(),  
  28.                     "ContactNumber": $("input[title='ContactNumber']").val(),   
  29.                     "Files": fileArray  
  30.                 });  
  31.                 createNewItemWithAttachments("BankDetails", data).then(  
  32.                     function () {  
  33.                         if (oLoader.close) setTimeout(function () { oLoader.close(); window.location.replace(_spPageContextInfo.siteAbsoluteUrl + "/Lists/BankDetails/AllItems.aspx"); }, 3000);  
  34.                          
  35.                     },  
  36.                     function (sender, args) {  
  37.                         console.log('Error occured' + args.get_message());  
  38.                     }  
  39.                 )  
  40.             }  
  41.              
  42.         }  
  43.    
  44.   
  45.     var createNewItemWithAttachments = function (listName, listValues) {  
  46.         var fileCountCheck = 0;  
  47.         var fileNames;  
  48.         var context = new SP.ClientContext.get_current();  
  49.         var dfd = $.Deferred();  
  50.         var targetList = context.get_web().get_lists().getByTitle(listName);  
  51.         context.load(targetList);  
  52.         var itemCreateInfo = new SP.ListItemCreationInformation();  
  53.         var listItem = targetList.addItem(itemCreateInfo);  
  54.         listItem.set_item("Name", listValues[0].Name);  
  55.         listItem.set_item("Address", listValues[0]. Address);  
  56.         listItem.set_item("City", listValues[0].City);  
  57.         listItem.set_item("ContactNumber", listValues[0].ContactNumber);  
  58.         listItem.update();  
  59.         context.executeQueryAsync(  
  60.             function () {  
  61.                 var id = listItem.get_id();  
  62.                 if (listValues[0].Files.length != 0) {  
  63.                     if (fileCountCheck <= listValues[0].Files.length - 1) {  
  64.                         loopFileUpload(listName, id, listValues, fileCountCheck).then(  
  65.                             function () {  
  66.                             },  
  67.                             function (sender, args) {  
  68.                                 console.log("Error uploading");  
  69.                                 dfd.reject(sender, args);  
  70.                             }  
  71.                         );  
  72.                     }  
  73.                 }  
  74.                 else {  
  75.                     dfd.resolve(fileCountCheck);  
  76.                 }  
  77.             },  
  78.             function (sender, args) {  
  79.                 console.log('Error occured' + args.get_message());  
  80.             }  
  81.         );  
  82.         return dfd.promise();  
  83.     }  
  84.   
  85.     function loopFileUpload(listName, id, listValues, fileCountCheck) {  
  86.         var dfd = $.Deferred();  
  87.         uploadFileHolder(listName, id, listValues[0].Files[fileCountCheck].Attachment).then(  
  88.             function (data) {  
  89.                 var objcontext = new SP.ClientContext();  
  90.                 var targetList = objcontext.get_web().get_lists().getByTitle(listName);  
  91.                 var listItem = targetList.getItemById(id);  
  92.                 objcontext.load(listItem);  
  93.                 objcontext.executeQueryAsync(function () {  
  94.                     console.log("Reload List Item- Success");  
  95.                     fileCountCheck++;  
  96.                     if (fileCountCheck <= listValues[0].Files.length - 1) {  
  97.                         loopFileUpload(listName, id, listValues, fileCountCheck);  
  98.                     } else {  
  99.                         console.log(fileCountCheck + ": Files uploaded");  
  100.                         attcount += fileCountCheck;  
  101.                         if (arraycount == attcount) {  
  102.                             if (oLoader.close) setTimeout(function () { oLoader.close(); window.location.replace(_spPageContextInfo.siteAbsoluteUrl + "/Lists/BankDetails/AllItems.aspx"); }, 3000);  
  103.                         }  
  104.   
  105.                     }  
  106.                 },  
  107.                 function (sender, args) {  
  108.                     console.log("Reload List Item- Fail" + args.get_message());  
  109.                 });  
  110.   
  111.             },  
  112.             function (sender, args) {  
  113.                 console.log("Not uploaded");  
  114.                 dfd.reject(sender, args);  
  115.             }  
  116.        );  
  117.         return dfd.promise();  
  118.     }  
  119.   
  120.     function uploadFileHolder(listName, id, file) {  
  121.         var deferred = $.Deferred();  
  122.         var fileName = file.name;  
  123.         getFileBuffer(file).then(  
  124.             function (buffer) {  
  125.                 var bytes = new Uint8Array(buffer);  
  126.                 var binary = '';  
  127.                 for (var b = 0; b < bytes.length; b++) {  
  128.                     binary += String.fromCharCode(bytes[b]);  
  129.                 }  
  130.                 var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";  
  131.                 console.log(' File size:' + bytes.length);  
  132.                 $.getScript(scriptbase + "SP.RequestExecutor.js"function () {  
  133.                     var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);  
  134.                     createitem.executeAsync({  
  135.                         url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')",  
  136.                         method: "POST",  
  137.                         binaryStringRequestBody: true,  
  138.                         body: binary,  
  139.                         success: fsucc,  
  140.                         error: ferr,  
  141.                         state: "Update"  
  142.                     });  
  143.                     function fsucc(data) {  
  144.                         console.log(data + ' uploaded successfully');  
  145.                         deferred.resolve(data);  
  146.                     }  
  147.                     function ferr(data) {  
  148.                         console.log(fileName + "not uploaded error");  
  149.                         deferred.reject(data);  
  150.                     }  
  151.                 });  
  152.   
  153.             },  
  154.             function (err) {  
  155.                 deferred.reject(err);  
  156.             }  
  157.         );  
  158.         return deferred.promise();  
  159.     }  
  160.     function getFileBuffer(file) {  
  161.         var deferred = $.Deferred();  
  162.         var reader = new FileReader();  
  163.         reader.onload = function (e) {  
  164.             deferred.resolve(e.target.result);  
  165.         }  
  166.         reader.onerror = function (e) {  
  167.             deferred.reject(e.target.error);  
  168.         }  
  169.         reader.readAsArrayBuffer(file);  
  170.         return deferred.promise();  
  171.     }  
  172.    
  173. </script>  

Final O/P

SharePoint