如何为FileReader编写回调?

时间:2017-10-24 13:34:38

标签: javascript filereader

我尝试上传多个附件。  首先,我从用户界面获取附件,然后我将它们转换为JSON,然后我需要进行服务器调用。 在此我使用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.

请帮助我实现这一目标。

1 个答案:

答案 0 :(得分:0)

您可以使用承诺:

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

jQuery也提供$ .when()函数:

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

使用promisejs,您可以执行以下操作:

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);
  });
}