user image

Published in : 2022-03-03

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?


Rakshit Date : 2022-03-04

Best answers


Best answers


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(); fr.onload=function(){ document.getElementById('result').textContent=fr.result; } fr.readAsText(this.files[0]); });</script>

Reference: Mozilla

Hope it will helpful for you.

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Simple HTML date picker is showing not showing calendar icon!
Publish date: 2022-03-01 | Comments: 2

Tag: Javascript

How to get audio input and audio output as one stream?
Publish date: 2022-02-13 | Comments: 2

Tag: Javascript

What is the use of package-lock JSON file?
Publish date: 2022-02-11 | Comments: 3

Tag: Javascript

jquery undefined function
Publish date: 2022-02-28 | Comments: 1

Tag: Javascript

Check if div have touch another div
Publish date: 2022-03-02 | Comments: 1

Tag: Javascript

How to toggle ( show and hide ) divs according to day hours?
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript

Help: How do I loop simple JSON objects to iterate all keys and values itself?
Publish date: 2022-03-06 | Comments: 1

Tag: Javascript