无法查看多个上传和预览的图像预览

时间:2018-04-27 13:08:43

标签: html file-upload 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);
    });

1 个答案:

答案 0 :(得分:0)

试试这个...

  $(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>