Sachchin Annam

Sachchin Annam

  • NA
  • 549
  • 50.9k

Conflict issue while updating attachments

Apr 1 2018 11:45 AM

Hello Techies,

I created a custom form which has dynamic subform as well. for eg the custom form consist of 3 sections:

  1. Parent form
  2. Attachment control
  3. Sub form with add/remove button for creating multiple subforms.

Here how my script works for adding the data:

  1. Parent form gets submitted and it returns item ID using jsom.
  2. And based on that item ID, Attachments are added to parent form and sub-form data gets added in another list.
But sometimes, i am facing conflict issue while adding multiple attachments of 2-3mb  and here is the code:
 
  1. if (flag == true) {  
  2.         oLoader = SP.UI.ModalDialog.showWaitScreenWithNoClose("Working on it""Creating a new Request...");  
  3.         var data = [];  
  4.         var fileArray = [];  
  5.         $("#attachFilesContainer input:file").each(function () {  
  6.             if ($(this)[0].files[0]) {  
  7.                 fileArray.push({ "Attachment": $(this)[0].files[0] });  
  8.             }  
  9.         });  
  10.         arraycount += fileArray.length;  
  11.   
  12.         data.push({  
  13.             "Column1": $("#txtColumn1").val(),  
  14.             "Column2": $("#Column2drpdown option:selected").text(),  
  15.             "Column3": $("#Column3drpdown option:selected").text(),  
  16.             "Column4": $("#Column4Drpdown :selected").text(),  
  17.             "Column5": newReqDate,//$("#txtColumn5CompletionDate").datepicker('getDate').format('MM/dd/yyyy'),   
  18.             "Column6": AccountName,//peoplepicker value  
  19.             "Column7": $("#Column7drpQuoteRequired :selected").text(),  
  20.             "Files": fileArray  
  21.         });  
  22.   
  23.         createItemWithAttachments("Parent", data).then(  
  24.            function () {  
  25.              
  26.                     oLoader.close();   
  27.                     window.location.replace(_spPageContextInfo.webAbsoluteUrl + "/Lists/Parent/AllItems.aspx");  
  28.   
  29.      
  30.                    //if (oLoader.close) setTimeout(function () { oLoader.close(); window.location.replace(_spPageContextInfo.webAbsoluteUrl + "/Lists/Test/AllItems.aspx"); }, 3000);  
  31.                //alert('Item created with Multiple attachments');  
  32.            },  
  33.              
  34.                    
  35.            function (sender, args) {  
  36.                console.log('Error occured' + args.get_message());  
  37.            }  
  38.              
  39.        )  
  40.             //oLoader.close();   
  41.            //window.location.replace(_spPageContextInfo.webAbsoluteUrl + "/Lists/Parent/AllItems.aspx");  
  42.   
  43.   
  44.   
  45.   
  46.     }  
  47. function createSubformItem(listName,i) {  
  48.     var listItem = {  
  49.           __metadata: { "type""SP.Data.SubFormListItem" },  
  50.                     "ParentID": id,  
  51.                     "SubColumn1":$("input[id='txtSubColumn1" + i + "']").val(),  
  52.                     "SubColumn2":$("input[id='txtSubColumn2" + i + "']").val(),  
  53.                     "SubColumn3":$("#SubColumn3drpdown" + i + " option:selected").val(),  
  54.                     "SubColumn4":$("#SubColumn4drpdown" + i + " option:selected").val()!="null" ? { "__metadata": { "type""Collection(Edm.String)" }, "results": $("#SubColumn4drpdown"+i+"").val() } : { "__metadata": { "type""Collection(Edm.String)" }, "results": [""] },  
  55.                     "SubColumn5":$("#SubColumn5drpdown" + i + " option:selected").val(),  
  56.                     "SubColumn6":$("input[id='txtSubColumn6" + i + "']").val(),  
  57.                     "SubColumn7":$("#SubColumn7drpdown" + i + " option:selected").val(),  
  58.                     "SubColumn8":$("input[id='txtSubColumn8" + i + "']").val(),  
  59.                     "SubColumn9":$("textarea[title='SubColumn9" + i + "']").val(),  
  60.                                            
  61.     };  
  62.     return $.ajax({  
  63.         url:"http://devapp/app/_api/web/lists/getbytitle('SubForm')/items",  
  64.         type: "POST",  
  65.         contentType: "application/json;odata=verbose",  
  66.         data: JSON.stringify(listItem),  
  67.         headers: {  
  68.             "Accept""application/json;odata=verbose",  
  69.             "X-RequestDigest": $("#__REQUESTDIGEST").val()  
  70.         }  
  71.     });  
  72. }  
  73.   
  74. var createItemWithAttachments = function (listName, listValues) {  
  75.     var fileCountCheck = 0;  
  76.     var fileNames;  
  77.     var context = new SP.ClientContext.get_current();  
  78.     var dfd = $.Deferred();  
  79.     var targetList = context.get_web().get_lists().getByTitle(listName);  
  80.     context.load(targetList);  
  81.     var singleUser = listValues[0].Column6 != "" ? SP.FieldUserValue.fromUser(listValues[0].Column1) : null;  
  82.     var itemCreateInfo = new SP.ListItemCreationInformation();  
  83.     var listItem = targetList.addItem(itemCreateInfo);  
  84.     listItem.set_item("Column1", listValues[0].Column1);  
  85.     listItem.set_item("Column2", listValues[0].Column2);  
  86.     listItem.set_item("Column3", listValues[0].Column3);  
  87.     listItem.set_item("Column4", listValues[0].Column4);  
  88.     listItem.set_item("Column5", listValues[0].Column5);  
  89.     listItem.set_item("Column6", singleUser);  
  90.     listItem.set_item("Column7", listValues[0].Column7);  
  91.   
  92.     listItem.update();  
  93.     for (i = 0; i <= count; i++)   
  94.                 {  
  95.   
  96.                     createSubformItem("SubForm",i);  
  97.                   
  98.                 }  
  99.   
  100.     context.executeQueryAsync(  
  101.         function () {  
  102.             id = listItem.get_id();  
  103.             if (listValues[0].Files.length != 0) {  
  104.                 if (fileCountCheck <= listValues[0].Files.length - 1) {  
  105.                     loopFileUpload(listName, id, listValues, fileCountCheck).then(  
  106.                         function () {  
  107.                         },  
  108.                         function (sender, args) {  
  109.                             console.log("Error uploading");  
  110.                             dfd.reject(sender, args);  
  111.                         }  
  112.                     );  
  113.                 }  
  114.             }  
  115.             else {  
  116.                 dfd.resolve(fileCountCheck);  
  117.             }  
  118.         },  
  119.         function (sender, args) {  
  120.             console.log('Error occured' + args.get_message());  
  121.         }  
  122.     );  
  123.     return dfd.promise();  
  124. }  
  125.   
  126. /*End of */  
  127.   
  128.   
  129. function loopFileUpload(listName, id, listValues, fileCountCheck) {  
  130.     var dfd = $.Deferred();  
  131.     uploadFile(listName, id, listValues[0].Files[fileCountCheck].Attachment).then(  
  132.         function (data) {  
  133.             var objcontext = new SP.ClientContext();  
  134.             var targetList = objcontext.get_web().get_lists().getByTitle(listName);  
  135.             var listItem = targetList.getItemById(id);  
  136.             objcontext.load(listItem);  
  137.             objcontext.executeQueryAsync(function () {  
  138.                 console.log("Reload List Item- Success");  
  139.                 fileCountCheck++;  
  140.                 if (fileCountCheck <= listValues[0].Files.length - 1) {  
  141.                     loopFileUpload(listName, id, listValues, fileCountCheck);  
  142.                 } else {  
  143.                     console.log(fileCountCheck + ": Files uploaded");  
  144.                     attcount += fileCountCheck;  
  145.                     if (arraycount == attcount) {  
  146.                      for (i = 0; i <= count; i++)   
  147.                     {  
  148.                         createSubformItem("SubForm",i);  
  149.                       
  150.                     }  
  151.                     oLoader.close();   
  152.                     window.location.replace(_spPageContextInfo.webAbsoluteUrl + "/Lists/ParentList/AllItems.aspx");  
  153.                           
  154.                     }  
  155.                       
  156.                 }  
  157.             },  
  158.             function (sender, args) {  
  159.                 console.log("Reload List Item- Fail" + args.get_message());  
  160.             });  
  161.   
  162.         },  
  163.         function (sender, args) {  
  164.             console.log("Not uploaded");  
  165.             dfd.reject(sender, args);  
  166.         }  
  167.    );  
  168.     return dfd.promise();  
  169. }  
  170. function uploadFile(listName, id, file) {  
  171.     var deferred = $.Deferred();  
  172.     var fileName = file.name;  
  173.     getFileBuffer(file).then(  
  174.         function (buffer) {  
  175.             var bytes = new Uint8Array(buffer);  
  176.             var binary = '';  
  177.             for (var b = 0; b < bytes.length; b++) {  
  178.                 binary += String.fromCharCode(bytes[b]);  
  179.             }  
  180.             var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";  
  181.             console.log(' File size:' + bytes.length);  
  182.             $.getScript(scriptbase + "SP.RequestExecutor.js"function () {  
  183.                 var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);  
  184.                 createitem.executeAsync({  
  185.                     url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')",  
  186.                     method: "POST",  
  187.                     binaryStringRequestBody: true,  
  188.                     body: binary,  
  189.                     success: fsucc,  
  190.                     error: ferr,  
  191.                     state: "Update"  
  192.                 });  
  193.                 function fsucc(data) {  
  194.                     console.log(data + ' uploaded successfully');  
  195.                     deferred.resolve(data);  
  196.                 }  
  197.                 function ferr(data) {  
  198.                     console.log(fileName + "not uploaded error");  
  199.                     deferred.reject(data);  
  200.                 }  
  201.             });  
  202.   
  203.         },  
  204.         function (err) {  
  205.             deferred.reject(err);  
  206.         }  
  207.     );  
  208.     return deferred.promise();  
  209. }  
  210. function getFileBuffer(file) {  
  211.     var deferred = $.Deferred();  
  212.     var reader = new FileReader();  
  213.     reader.onload = function (e) {  
  214.         deferred.resolve(e.target.result);  
  215.     }  
  216.     reader.onerror = function (e) {  
  217.         deferred.reject(e.target.error);  
  218.     }  
  219.     reader.readAsArrayBuffer(file);  
  220.     return deferred.promise();  
  221. }  
Please let me know where am I going wrong. 
 

Answers (3)