If we get the value of location from input it returns something like-"file:///C:/fakepath/image.jpg". But when I set this value to the src of a image it says file not found.
How can I get the correct path of the image and set it to the source of the image?
Html:
<label for="inputId">file dialog</label>
<input type="file" id="inputId"/>
<button onclick="setImage()">Show Image</button>
<br>
<img id="image"src="" width="600px" height="400px">
JS:
var img = document.getElementById("image");
function setImage() {
var fileName = document.getElementById("inputId").value;
img.src = fileName;
}
You need to read the file and set its base64
data to the src
of the image:
var img = document.getElementById("image");
function setImage() {
const files = document.getElementById("inputId").files;
if (!files || files.length==0)
return;
const file = files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
img.src = reader.result;
};
}
<label for="inputId">file dialog</label>
<input type="file" id="inputId"/>
<button onclick="setImage()">Show Image</button>
<br>
<img id="image"src="" width="600px" height="400px">