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

I found the image upload code, I'm confused what is 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]); }; 
+5
source share
3 answers
  • .readAsDataURL() returns a URL representing the file data as a base64 encoded string

  • .readAsArrayBuffer() returns an ArrayBuffer representing the Data file

  • .readAsText() returns the file data as a text string.

More details ... this FileReader doc.

+7
source

readAsDataURL() will return a string that can be inserted into the url attribute of the HTML tag (for example: src= in img). For the img tag, which will render the image effectively just as if src were the address in the file that was read. This is a conversion (larger) of the original contents of the file.

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

+1
source

I think that if you want to have the function of downloading files, and then show the user a preview of the file they selected on their PC and .readAsDataURL() , then use .readAsDataURL() .

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

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

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

0
source

Source: https://habr.com/ru/post/1246700/


All Articles