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]);
};
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.
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.
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.
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.
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.
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With