Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between readAsDataURL() and readAsArrayBuffer() and readAsText() in JavaScript FileReader

I have found a code of image uploading preview, I'm confused what's going on in FileRead() ?

var openFile = function(event) {
    var input = event.target;

    var reader = new FileReader();
    reader.onload = function() {
        var dataURL = reader.result;
        var output = document.getElementById('output');
        console.log(dataURL)
        output.src = dataURL;
    };
    reader.readAsDataURL(input.files[0]);
};
like image 981
Gowrishankar RJ Avatar asked Apr 08 '16 12:04

Gowrishankar RJ


People also ask

What does FileReader do in JavaScript?

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 the readAsText () function return?

The readAsText() method is used to read the contents of the specified Blob or File . When the read operation is complete, the readyState is changed to DONE , the loadend event is triggered, and the result property contains the contents of the file as a text string.

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.


3 Answers

I think if you want to have a file upload functionality and then show the user a preview of the file they they chose from their PC and about to upload, then use .readAsDataURL().

If you want to manipulate a text file, use .readAsText()

If you want to manipulate something like an image (convert a jpeg to PNG for example) then use .readAsArrayBuffer().

There is a fourth method, .readAsBinaryString, but the Mozilla documentation suggests using .readAsArrayBuffer() instead.

like image 160
Fabian Madurai Avatar answered Oct 25 '22 18:10

Fabian Madurai


readAsDataURL() will return a string that can be pasted into the url attribute of an HTML tag (e.g.: src= in an img). For an img tag, that will effectively display the image just like if src was an address to the file that was read. It is a transformation (bigger) of the original file content.

readAsText() will return a string of characters that can be parsed by JavaScript functions or displayed in textarea and likely to be understood by the user. This is usually useful for reading text files.

like image 44
Boog Dow Avatar answered Oct 25 '22 18:10

Boog Dow


  • .readAsDataURL() return a URL representing the file's data as a base64 encoded string

  • .readAsArrayBuffer() return an ArrayBuffer representing the file's data

  • .readAsText() return the file's data as a text string.

For more info check this FileReader doc.

like image 26
Matteo Baldi Avatar answered Oct 25 '22 18:10

Matteo Baldi