Need a way to display an uploaded image from an HTML form inside a div for the user to see? Here's a handy solution:
In a recent project of mine, I successfully allowed users to upload image files. You can achieve this by using the onchange event of the input field to detect when a file is selected. Then, access the selected file using the files property of the input field as shown in the example below:
<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
}
If you want to display the selected file as an image within a div, consider using the URL.createObjectURL() method to create a URL that references the file:
var url = URL.createObjectURL(file);
document.getElementById("img").src = url;
The file.name property will give you the filename, and URL.createObjectURL(file) allows you to set the source of an image tag with the created URL object.