I've been looking around and haven't been able to find whether this is possible or not.
This is what I would like to happen before submitted: When a user selects a file to be uploaded, I want to grab the image's data and convert it to base64. After it's been converted, I would like to either directly display it in a div
or have it sent to the server via AJAX, then displayed in the div
.
Below is basically what I'm looking for:
// index.php
<input type="file" name="img" id="img" onChange="displayImg(this)">
// displayImg.js
function displayImg(img) {
imgData = img.?; // How do I do this?
img64 = // I know how to do this.
document.write("<img src='data:image/jpeg;base64,"+img64+"' />");
}
I've been looking around and haven't been able to find whether this is possible or not.
This is what I would like to happen before submitted: When a user selects a file to be uploaded, I want to grab the image's data and convert it to base64. After it's been converted, I would like to either directly display it in a div
or have it sent to the server via AJAX, then displayed in the div
.
Below is basically what I'm looking for:
// index.php
<input type="file" name="img" id="img" onChange="displayImg(this)">
// displayImg.js
function displayImg(img) {
imgData = img.?; // How do I do this?
img64 = // I know how to do this.
document.write("<img src='data:image/jpeg;base64,"+img64+"' />");
}
Share
Improve this question
edited Sep 11, 2011 at 2:39
Lightness Races in Orbit
385k77 gold badges666 silver badges1.1k bronze badges
asked Sep 10, 2011 at 15:16
PetePete
411 silver badge3 bronze badges
0
1 Answer
Reset to default 8function displayImage(evt){
var files = evt.target.files;
var reader = new FileReader();
reader.onload = function(frEvent) {
document.getElementById("renderImage").innerHTML = '<img src="'+frEvent.target.result+'" />';
}
reader.readAsDataURL(files[0]);
}
The code above works for me. It lacks verification and all that good stuff, but this should be a good starting point for you.