无法查看多个上传和预览的图像预览
Unable to view image preview for multiple upload and preview
我正在使用多张图片上传并显示上传预览,但以下代码不起作用
HTML
<form id="mainform" method="post" enctype="multipart/form-data">
<div class="upload-ad-photos">
<label>Photos for your ad :</label>
<input type="file" name="img1" id="img1"><br>
<img id="preview-img1" />
<br>
<div class="clearfix"></div>
<input type="file" name="img1" id="img2"><br>
<img id="preview-img2" />
<br>
</div>
</form>
脚本
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
imgId = '#preview-' + $(input).attr('id');
$(imgId).attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$("form#mainform div input[type='file']").change(function () {
readURL(this);
});
试试这个...
$(function() {
// Multiple images preview in browser
var readURL = function(input) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo('#preview-img1');
}
reader.readAsDataURL(input.files[i]);
}
}
};
$("form#mainform div input[type='file']").change(function () {
readURL(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mainform" method="post" enctype="multipart/form-data">
<div class="upload-ad-photos">
<input type="file" name="img1" id="img1" multiple><br>
<div id="preview-img1"></div>
</div>
</form>
我正在使用多张图片上传并显示上传预览,但以下代码不起作用
HTML
<form id="mainform" method="post" enctype="multipart/form-data">
<div class="upload-ad-photos">
<label>Photos for your ad :</label>
<input type="file" name="img1" id="img1"><br>
<img id="preview-img1" />
<br>
<div class="clearfix"></div>
<input type="file" name="img1" id="img2"><br>
<img id="preview-img2" />
<br>
</div>
</form>
脚本
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
imgId = '#preview-' + $(input).attr('id');
$(imgId).attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$("form#mainform div input[type='file']").change(function () {
readURL(this);
});
试试这个...
$(function() {
// Multiple images preview in browser
var readURL = function(input) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo('#preview-img1');
}
reader.readAsDataURL(input.files[i]);
}
}
};
$("form#mainform div input[type='file']").change(function () {
readURL(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mainform" method="post" enctype="multipart/form-data">
<div class="upload-ad-photos">
<input type="file" name="img1" id="img1" multiple><br>
<div id="preview-img1"></div>
</div>
</form>