Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  82] [ 3]  / answers: 1 / hits: 32366  / 10 Years ago, fri, march 7, 2014, 12:00:00

I would like to choose a file and display the image on the browser.
I tried inserting the direct image path and it worked.



The problem now is, how can I display the image from the <input type=file> ?



Here is what my code looks like:



function myFunction() {
var file = document.getElementById('file').files[0];
var reader = new FileReader();

reader.onloadend = function {
var image = document.createElement(img);
image.src = reader
image.height = 200;
image.width = 200;

document.body.appendChild(image);
}
}




<input type=file name=filename id=file>
<button type=button onclick='myFunction()'>Display</button>

More From » javascript

 Answers
44
function myFunction() {

var file = document.getElementById('file').files[0];
var reader = new FileReader();
// it's onload event and you forgot (parameters)
reader.onload = function(e) {
var image = document.createElement(img);
// the result image data
image.src = e.target.result;
document.body.appendChild(image);
}
// you have to declare the file loading
reader.readAsDataURL(file);
}


http://jsfiddle.net/Bwj2D/11/ working example


[#72107] Wednesday, March 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shawn

Total Points: 507
Total Questions: 103
Total Answers: 111

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
shawn questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Tue, Jun 8, 21, 00:00, 3 Years ago
Sat, Feb 27, 21, 00:00, 3 Years ago
Sat, Dec 19, 20, 00:00, 4 Years ago
Sat, May 9, 20, 00:00, 4 Years ago
;