Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show user uploaded image files from input field in a div

I have an input field of type file and whenever user uploads by clicking on that input, I want to show them the file they have selected, How can I do that using JS.

I have an input field of type file and whenever user uploads by clicking on that input, I want to show them the file they have selected, How can I do that using JS. I don’t know how to do it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you want to get input as file form html form and display the image inside HTML div to show user which file they have selected.

I have implement this in my project where user are allowed to upload image file hope this will help you. You can use the onchange event of the input field to detect when a user has selected a file. Then, you can use the files property of the input field to access the selected file(s). Here’s an example:

 <input type="file" id="file-input" onchange="showSelectedFile()">



function showSelectedFile() {
    var input = document.getElementById("file-input");
    var file = input.files[0];
    console.log(file.name); // Display the file name
 }

You can also use

URL.createObjectURL()

method to create a URL that can be used to refer to the file in a tag.

 var url = URL.createObjectURL(file);
 document.getElementById("img").src = url;

file.name will give the name of the selected file and URL.createObjectURL(file) will create a URL object for the selected file, this url can be used to set the source of an image tag.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading