Difference between readAsDataURL() and readAsArrayBuffer() and readAsText() in JavaScript FileReader
.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.
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.
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.