此代码将覆盖多个输入标签的图像 并且图像预览显示在所有标签的底部 我尝试了很多!
我想在一页上预览多张图像。 请告诉我如何循环使用此脚本。
if (window.FileReader) {
var reader = new FileReader(),
rFilter = /^(image\/bmp|image\/cis-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x-cmu-raster|image\/x-cmx|image\/x-icon|image\/x-portable-anymap|image\/x-portable-bitmap|image\/x-portable-graymap|image\/x-portable-pixmap|image\/x-rgb|image\/x-xbitmap|image\/x-xpixmap|image\/x-xwindowdump)$/i;
reader.onload = function(oFREvent) {
preview = document.getElementById("uploadPreview1")
preview.src = oFREvent.target.result;
preview.style.display = "block";
};
function doTest1() {
if (document.getElementById("myfile1").files.length === 0) {
return;
}
var file = document.getElementById("myfile1").files[0];
if (!rFilter.test(file.type)) {
alert("You must select a valid image file!");
return;
}
reader.readAsDataURL(file);
}
reader.onload = function(oFREvent) {
preview = document.getElementById("uploadPreview2")
preview.src = oFREvent.target.result;
preview.style.display = "block";
};
function doTest2() {
if (document.getElementById("myfile2").files.length === 0) {
return;
}
var file = document.getElementById("myfile2").files[0];
if (!rFilter.test(file.type)) {
alert("You must select a valid image file!");
return;
}
reader.readAsDataURL(file);
}
} else {
alert("FileReader object not found :( \nTry using Chrome, Firefox or WebKit");
}
<html>
<body>
<div>
<p><input type="file" id="myfile1" name="myfile1" size="30" onchange="doTest1()"></p>
<img id="uploadPreview1" src="" width="100" style="display:none" />
</div>
<br><br><br>
<div>
<p><input type="file" id="myfile2" name="myfile2" size="30" onchange="doTest2()"></p>
<img id="uploadPreview2" src="" width="100" style="display:none" />
</div>
</body>
</html>
答案 0 :(得分:0)
仅需一点提示:您正在重写reader.onload处理函数。因此,图片始终显示为uploadPreview2 img的src。