user image

Shilpa
Published in : 2022-03-03

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

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?

Comments

Rakshit Date : 2022-03-04

Best answers

34

Best answers

34

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

Vanilla JavaScript Next & prev Navigation
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript

javascript: Uncaught TypeError: undefined is not a function
Publish date: 2022-03-02 | Comments: 2

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

How select specific tag in jQuery using if else statement?
Publish date: 2022-02-27 | Comments: 1

Tag: Javascript

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

Tag: Javascript

Adding an id number at the first index to an array of objects
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript