Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome FileReader

Can someone give me an example of using the FileReader API go get contents of a file in chrome?

It seems to be returning undefined for me.

<!doctype html>
<html>
<script>
function handle_files(files) {
  console.log(files)
  reader = new FileReader()
  ret = []
  for (i = 0; i < files.length; i++) {
    file = files[i]
    console.log(file)
    text = reader.readAsText(file) //readAsdataURL
    console.log(text) //undefined
    ret.push(text)
  }
  console.log(ret) // [undefined]

}
</script>
<body>
FileReader Test
<input type="file" onchange="handle_files(this.files)">
</body>
</html>
like image 616
Drew LeSueur Avatar asked Nov 04 '10 20:11

Drew LeSueur


People also ask

What is the use of FileReader?

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

What does FileReader return?

The FileReader result property returns the file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.

How does FileReader work JavaScript?

Introduction to the JavaScript FileReader API And JavaScript uses the FileList object to hold the File objects. To read the content of a file, you use the FileReader object. Note that the FileReader only can access the files you selected via drag & drop or file input.

How do you use readAsDataURL?

The readAsDataURL method is used to read the contents of the specified Blob or File . When the read operation is finished, the readyState becomes DONE , and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.


2 Answers

My problem was that I assumed FileReader was sychronous. Here is the right way to do it. If you are on chrome, this code has to be running on a server (localhost or on a site). It won't work with a local file.

<!doctype html>
<html>
<script>
function handle_files(files) {
  for (i = 0; i < files.length; i++) {
    file = files[i]
    console.log(file)
    var reader = new FileReader()
    ret = []
    reader.onload = function(e) {
      console.log(e.target.result)
    }
    reader.onerror = function(stuff) {
      console.log("error", stuff)
      console.log (stuff.getMessage())
    }
    reader.readAsText(file) //readAsdataURL
  }

}
</script>
<body>
FileReader that works!
<input type="file" multiple onchange="handle_files(this.files)">
</body>
</html>
like image 196
Drew LeSueur Avatar answered Sep 29 '22 11:09

Drew LeSueur


The File API FileReader object operates the same way in Chrome as it does in FireFox, Opera, or Internet Explorer 10 (Yup, works in IE).

Simple Example

You start by declaring a new instance of the reader:

var reader = new FileReader();

Define your callbacks for its various events:

reader.onloadend = function(){
    document.body.style.backgroundImage = "url(" + this.result + ")";
}

And then pass it something to read:

reader.readAsDataURL(file);

Fiddle: http://jsfiddle.net/jonathansampson/K3A9r/

Handling Multiple Files

When you're working with multiple files, things are a bit different. While it's clear we need to cycle over the resulting FileList, we'll also need to use a closure to prevent file data from getting tampered with over numerous iterations:

    // Continue only if we have proper support
    if ( window.FileReader ) {

      // Provide our logic upon the change even of our input
      document.getElementById("collection").onchange = function(){

        // Couple variables for handling each file
        var counter = -1, file;

        // Cycle over all files
        while ( file = this.files[ ++counter ] ) {

          // Create a reader for this particular file
          var reader = new FileReader();

          // Respond to the onloadend event of the reader
          reader.onloadend = (function(file){
            return function(){
              var image = new Image();
              image.height = 100;
              image.title = file.name;
              image.src = /^image/.test(file.type) ? this.result : "t9QlH.png";
              document.body.appendChild( image );
            }
          })(file);

          // Begin reading data for this file
          reader.readAsDataURL( file );
        }
      }
    }​

Fiddle: http://jsfiddle.net/jonathansampson/jPTV3/

Feature Detection

Although FileReader is available in nearly all modern browsers, you still want to be sure you don't cause any ruckus for users on older browsers. Prior to using the FileReader, be sure to check the window object for its presence:

if ( window.FileReader ) {
    // Safe to use FileReader
}

Running Locally, From Chrome

I should note that running this in a file:/// path in Chrome will result in a broken experience. By default, current versions of Chrome don't permit file:/// pages to access other files. You can change this behavior loading Chrome with the --allow-file-access-from-files flag.

enter image description here

Note, this method will only permit file access for files on the instance of the browser it was opened with. If you want this to be the case for all browser instances into the future, you could modify the shortcut from your desktop. Simply right-click the Chrome shortcut, and go to properties. Next, add the flag to the end of the target.

like image 35
Sampson Avatar answered Sep 29 '22 12:09

Sampson