I am trying to implement javascript's FileReader Interface in my project.
The requirement: There is a file input field which is "multiple" enabled, I want the user should select a few images and should see the images on the page even before hitting submit(so that (s)he may delete it if (s)he wants!). But the problem is that only one image is displayed on the screen. The tags are created but the src is empty except for the last image.
The code:
<html>
<head>
<meta charset="windows-1252">
<title></title>
</head>
<body>
<div>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="abc[]" multiple/>
<input type="submit"/>
</form>
</div>
<img id="image0"/>
</body>
<script src="resources/js/jquery-2.1.3.min.js" type="text/javascript"></script>
<script>
$('document').ready(function () {
$("input[name='abc[]']").change(function (e) {
console.log(e.originalEvent.srcElement.files.length);
for (var i = 1; i <= e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i-1];
var img = document.createElement("img");
img.id = "image"+i;
var reader = new FileReader();
reader.onloadend = function () {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("#image"+(i-1)).after(img);
}
});
});
</script>
For Example, in the image selection popup if I have selected img1. img2 and img3, only img3 is displayed. however, on hitting submit I do get all the images at the server side:
What am I missing here?