Home > Software design >  How to show user uploaded image files from input field in a div
How to show user uploaded image files from input field in a div

Time:01-27

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.

CodePudding user response:

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.

  • Related