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

Final O/P

SharePoint