Shilpa
3 Mar 2022
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
4 Mar 2022
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.
[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.
© 2024 Copyrights reserved for web-brackets.com