You can do some work to stylize it, but here's the general idea:
Let's say you have some very simple markup like this:
<!-- language: lang-html -->
<input type='file' />
<img id="myImg" src="#" alt="your image" />
- You want to tap into the
change
event of the <input type='file' />
element.
- Once there, check to see if any files have been selected, and if so, if the first file in the array exists.
- Then create a new
FileReader
object. We'll tell this object two things:
- When it raises the
onload
event, it should call a function imageIsLoaded
.
- Then take the data from the first file and read it in.
- When this completes it will raise the event in step one
In JavaScript, that'll look like this:
<!-- language: lang-js -->
$(":file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
};
In this example, when the image is loaded, we'll replace the source attribute of the img we have in markup in the imageIsLoaded
function.