具有图像预览选项,显示所选图像的拇指。
考虑以下HTML,
HTML:
<input type="file" multiple accept="image/x-png,image/gif,image/jpeg" title="Upload Image" id="gallery_img" name="roomimage[]" />
用于在浏览器中预览图片的代码:
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#gallery").on("change", function(e) {
var fileName = document.getElementById("gallery").value;
var idxDot = fileName.lastIndexOf(".") + 1;
var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//TO DO
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"imgPreview\">" +
"<img id=\"image\" name=\"image[]\" class=\"imageThumb\" src=\"" + e.target.result + "\"/>" +
"<span class=\"remove icon-error\" title=\"Close\"></span>" +
"</span>").insertAfter(".gallery_section");
$(".remove").click(function(){
$(this).parent(".imgPreview").remove();
});
});
fileReader.readAsDataURL(f);
}
}else{
alert("Only jpg/jpeg and png files are allowed!");
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
选择带有上述html的文件时,一切正常。我可以选择多个图像,我可以通过ajax上传多个图像。
AJAX:
var formData = new FormData($("#room_form")[0]);
var url=$("#room_form").attr("action");
$.ajax({
method: "POST",
data: formData,
url: url,
cache: false,
contentType: false,
processData: false,
})
.success(function(data) {
loaderHide();
setTimeout(function() {
window.location.reload();
}, 1000);
}).
fail(function(data) {
loaderHide();
});
上述所有方法都可以。
问题:
当我选择3个文件时。并在预览中显示这3个文件。
再次我选择另外2个文件,现在预览显示总共5个文件。
但在<input type="file"
中只有2个文件。我搜索并发现它是默认行为。
在具有原始图像作为基础64编码图像的图像源im中。我需要将此图像发送到PHP文件。我怎么能这样做?
答案 0 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="file" multiple accept="image/x-png,image/gif,image/jpeg" title="Upload Image" id="gallery_img" name="roomimage" />
<div class="gallery_section">
</body>
<script>
$(document).on('change','#gallery_img',function(evt){
var files = evt.target.files; // FileList object
// 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.*')) {
return;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
$('.gallery_section').append('<span class="imgPreview"><img id="image" name="image[]" class="imageThumb" src="'+e.target.result+'"><span class="remove icon-error" title="Close"></span></span>');
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
});
</script>
</html>
&#13;