我正在尝试上传多个图片并使用javascript放置在单独的img标签中。这就是我尝试过的,
MyJsp.jsp:
<div>
<img alt="Image1" id="Image1" src="" width="130px" height="90px"><br><br>
<img alt="Image2" id="Image2" src="" width="130px" height="90px"><br><br>
<img alt="Image3" id="Image3" src="" width="130px" height="90px"><br><br>
<img alt="Image4" id="Image4" src="" width="130px" height="90px"><br><br>
<img alt="Image5" id="Image5" src="" width="130px" height="90px"><br><br>
</div>
<input type="file" id="files" name="files[]" accept="image/gif,image/jpeg"/ multiple>
<input type="text" id="imginsert" value="1">
MyJS.js:
$(function(){
document.querySelector('#files').addEventListener('change', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// alert("1");
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var count=$('#imginsert').val();
if(count==1){
$('#Image1').attr("src",e.target.result);
$('#imginsert').val('2');
//alert("first :"+e.target.result);
}
else if(count==2)
{
//alert("else if 1");
$('#Image2').attr("src",e.target.result);
$('#imginsert').val('3');
//alert("2 :"+e.target.result);
}
else if(count==3)
{
//alert("else if 2");
$('#Image3').prop("src",e.target.result);
$('#imginsert').val('4');
//alert("3 :"+e.target.result);
}
else if(count==4)
{
$('#Image4').prop("src",e.target.result);
$('#imginsert').val('5');
//alert("4 :"+e.target.result);
}
else if(count==5)
{
$('#Image5').prop("src",e.target.result);
$('#imginsert').val('6');
//alert("5 :"+e.target.result);
}
else
{
alert("You can upload only 5 images.");
}
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
});
如果我上传Img1.jpg,Img2.jpg,Img3.jpg,Img4.jpg,Img5.jpg意味着OP是:
Img2.jpg
Img4.jpg
Img1.jpg
Img3.jpg
Img5.jpg
我期待的OP是:
Img1.jpg
Img2.jpg
Img3.jpg
Img4.jpg
Img5.jpg
我错误地按照上传图片顺序排列?
答案 0 :(得分:4)
readAsDataURL
是异步的,因此您无法保证它们会以任何顺序完成。只需使用您的文件
reader.onload = (function(theFile, count) {
return function(e) {
if (count > 5)
{
alert("You can upload only 5 images.");
}
else{
$('#Image'+count).prop("src",e.target.result);
}
};
})(f,i+1);