html:
<div class="right">
<div class="imgList">
</div>
<div class="add">
<div class="icon"></div>
<div class="text">上传凭证<br>(最多9张)</div>
</div>
<input type="file" name="images[]" onchange="choose_files()" accept="image/*" multiple style="display: none">
</div>
js:
$('.right .add').click(function () {
$('.right input[type=file]').trigger('click')
})
imageCount = 0; // 图片总数
imgList = []; // 图片组
function choose_files() {
console.log("选择文件");
var files = $('.right input[type=file]')[0].files;
if (imageCount > 9) {
alert('图片已达上限!');
return false;
}
var html = '';
for (let i = 0; i < files.length; i++) {
imageCount++;
// 通过 FileReader 实现 图片预览
var reader = new FileReader();
reader._imageCount = imageCount
reader.readAsDataURL(files[i])
reader.onload = function (re) {
// re.target.result就是读出的文件base64编码字符串
$('.img.img-' + re.target._imageCount + ' img').attr('src', re.target.result)
}
html = html + '<div class="img img-' + imageCount + '"><img src="" alt=""></div>';
imgList.push(files[i])
}
$('.right .imgList').append(html);
}