1

I'm trying to upload multiple attachments. First I'm getting attachments from user interface, then I'm converting them into JSON , then I need to make a server call. In this I'm using FileReader.

        //showing ajax loader
        component.set("v.showLoadingSpinner", true);

       //getting attached files
        var files = component.find("fileId").get("v.files");
        var details = {};    //JS Object need to send server
        details.files = [];

        for (var i = 0; i < files.length; i++) 
        {      
            (function(file) {
                var name = file.name;
                var reader = new FileReader(); 
                reader.fName = files[i]['name'];
                reader.fType = files[i]['type'];
                reader.i = i;
                reader.onload = function(e) {
                    var fileContents = reader.result;
                    var base64 = 'base64,';
                    var dataStart = fileContents.indexOf(base64) + base64.length;
                    fileContents = fileContents.substring(dataStart);
                    var startPosition = 0;
                    var endPosition = Math.min(fileContents.length, startPosition + 750000);
                    var getchunk = fileContents.substring(startPosition, endPosition);
                    var fDetails = {};
                    fDetails.fileName = reader.fName;
                    fDetails.base64Data = encodeURIComponent(getchunk);
                    fDetails.contentType = reader.fType;
                    details.files.push(fDetails);

                }
                reader.readAsDataURL(file);
            })(files[i]);

     // I want to make a server call here with data in "details" object.
   console.log(details);   

But I'm not getting data in above console log.

Please help me to achieve this.

2

1 Answer 1

1

You can use promises :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://davidwalsh.name/promises

https://developers.google.com/web/fundamentals/primers/promises

Also jQuery provide $.when() function :

https://api.jquery.com/jquery.when/

And with promisejs you can do something like this :

function readJSON(filename){
  return new Promise(function (fulfill, reject){
    readFile(filename, 'utf8').done(function (res){
      try {
        fulfill(JSON.parse(res));
      } catch (ex) {
        reject(ex);
      }
    }, reject);
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.