3 Mar 2022

Can I read a local json, image or text file from Javascript?


I am using a simple HTML input file to get the file data from the client browser. When they upload a file, I want to show a preview of the file, with text or JSON file - whatever the user uploads. But I am not sure about javascript to read the files on the client-side.

My HTML code is,

<input type="file" name="inputfile" id="inputfile"> 

I want to show the preview on below code with ‘<pre></pre>’ tag.

Document type can be anything like, jpeg, jpg, png, txt, json etc. So how do I show the preview of the file?



4 Mar 2022

Best Answer

best answer

In javascript they are giving support to read the file bytes and so you can render it on your page using following events.

  • FileReader.readAsArrayBuffer(): It contains an ArrayBuffer representing the file’s data.
  • FileReader.readAsBinaryString(): It contains the raw binary data from the file as a string.
  • FileReader.readAsDataURL(): It contains a URL representing the file’s data.
  • FileReader.readAsText(): It contains the contents of the file as a text string with default encoding in UTF-8 Format. [This is usable for your case]`

Use the following code to set preview for your uploaded file.

<input type="file" name="inputfile" id="inputfile">

Show your text file data in 'pre' tag.

<pre id="result"></pre>

Your javascript function and its usage: Input Text file.

<script type="text/javascript">
 document.getElementById('inputfile').addEventListener('change', function() {

 var fr=new FileReader();


Reference: Mozilla

Hope it will helpful for you.

© 2023 Copyrights reserved for