0

We are trying to save an attachment to multiple list items created concurrently. The PDF files are created dynamically using jspdf and stored against the list items

Below are the functions that create list item attachment by calling a common function named addItem().

Functions that call addItem()

function p1()
{
   CreateItem(fromEmail,distEmail,ccEmail,subject,body).then(function(resp){
                        
   console.log(resp);
   var Lid = resp.d.Id; // gets the list item ID
   var PDFStream = PDFArray; // Global Variable to get the jsPDF File
   var Fname = DFileName; // Global Variable to get the name of the attachment
   addItem(Lid,PDFStream,Fname);
  });
}

function p2()
{
   CreateItem(fromEmail,distEmail,ccEmail,subject,body).then(function(resp){
                        
   console.log(resp);
   var Lid = resp.d.Id; // gets the list item ID
   var PDFStream = PDFArray; // Global Variable to get the jsPDF File
   var Fname = DFileName; // Global Variable to get the name of the attachment
   addItem(Lid,PDFStream,Fname);
  });
}

Function to add attachment

function addItem(Lid,PDFFile,Fname) {
                        
            var File = PDFFile;
            var deferred = $.Deferred();           

                $.ajax({
                    url: _spPageContextInfo.webAbsoluteUrl +
                     "/_api/web/lists/getbytitle('ExtEmailsList')/items(" + Lid + ")/AttachmentFiles/add(FileName='"+Fname+"')",
                    type: 'POST',
                    data: File,
                    processData: false,
                    headers: {
                        "Accept": "application/json; odata=verbose",
                        "content-type": "application/json; odata=verbose",
                        "X-RequestDigest": $('#__REQUESTDIGEST').val(),
                        "content-length": File.length
                    },
                    success: function (data) {          
                    deferred.resolve(data);
                    },
        
                    error: function (err) {
                    deferred.reject(err);
                    }
               }); // ajax | POST      
        return deferred.promise();    
      };

Create Item Function

function CreateItem(from,recipient,ccing,subject,body) {
    var deferred = $.Deferred();
    var _urlExtrnList = "ExtEmailsList";
    var _data = {
        __metadata: { 'type': 'SP.Data.ExtEmailsListListItem' },
        Title: subject,
        fromEmail:from,
        toEmail:recipient,
        ccEmail:ccing,
        emailSubject:subject,
        emailBody:body
    };
    
    // Upload the document and return current doc details.
    saveNewListItem(_data,_urlExtrnList).then(function(response){
        deferred.resolve(response);
    },function(status){
        deferred.reject(status);        
    });
    
    return deferred.promise();
}; // CreateItem() | Ends!

The above function is called multiple times , However the function intermittently creates the attachment and the other times it fails and the attachment column is blank. Say function 1 calls addItem , it creates the attachment however the call from function 2 fails and vice versa.

I tried debugging , However there are no errors. Would appreciate if anyone could let us know how we can get this to work with multiple functions calling addItem().

Thanks in advance

0

This code works for me:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>
<input id="my-attachments" type="file" fileread="run.AttachmentData" fileinfo="run.AttachmentInfo" />
<script>
$(document).ready(function() {

var ID = [1,2,4];
var listname = "test5";

$("#my-attachments").change(function() {

 var file = $(this)[0].files[0];

 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) {
   
for(let i=0;i<ID.length;i++){
  $.ajax({
   url: _spPageContextInfo.webAbsoluteUrl +
    "/_api/web/lists/getbytitle('" + listname + "')/items(" + ID[i] + ")/AttachmentFiles/add(FileName='" + file.name + "')",
   method: 'POST',
   data: buffer,
   processData: false,
   headers: {
    "Accept": "application/json; odata=verbose",
    "content-type": "application/json; odata=verbose",
    "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
    
   }
  });
}
 

 });

});
});

</script>

If you need further help, please share the full code.

4
  • Thank you for the response , I am not attaching a file from fileinput. The file is being generated using jspdf and being sent to addItem() function which is failing intermittently. Please let me know if you need more details
    – Vivek
    Jan 25 at 8:45
  • Could you share the CreateItem function?
    – Amos
    Jan 25 at 9:19
  • Thanks for the assistance Amos , I have updated the post
    – Vivek
    Jan 25 at 9:39
  • any update on this Amos?
    – Vivek
    Jan 26 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.