Search code examples
javascripthtmlfilereaderfileapi

File uploading via FileAPI


I need to read multiple files into a single function A. I need to use FileAPI for it. But FileReader performs an asynchronous download. Can I get the contents of all files at the end of function A without exiting, or not?


Solution

  • Just to be perfectly clear, FileReader isn't downloading anything. It is asynchronously reading the File contents (as it appears on disk) into memory.

    To do what you want, just keep track of the read files and call a callback when they're all done:

    document.querySelector('[type="file"]').change = function(e) {
      handleFiles(toArray(e.target.files), function(results) {
        // results is an Array containing the FileReader results.
        alert('Done!');
      });
    
    function toArray(list) {
      return Array.prototype.slice.call(list || [], 0);
    }
    
    function handleFiles(files, callback) {
      var results = [];
    
      files.forEach(function(file, i) {
        var reader = new FileReader();
    
        // Closure to capture the file information.
        reader.onload = function(e) {
          results.push(e.target.result);
          if (results.length == files.length) {
            callback(results);
          }
        };
        reader.readAsDataURL(file);
      });
    }
    

    Try it: http://jsbin.com/epatel/3/edit#html,live