替换并预览多个图像上传

时间:2017-07-12 05:49:46

标签: javascript php jquery image file-upload

我使用此代码动态显示图像

    <?php
        $query = "SELECT post_gallery_img FROM posts WHERE post_id = $get_post_id";
        $select_gallery_imgs = mysqli_query($connection, $query);

        while($row = mysqli_fetch_assoc($select_gallery_imgs)) {
            $post_gallery_img = $row['post_gallery_img'];

            $post_gallery_img = explode(',', $row['post_gallery_img']);

            foreach($post_gallery_img as $out) {
                echo '<img class="imgFile" id="editPostGalleryImgs" src="../userImages/' . $out . '" alt="Post Image">';
            }
        }
    ?>

结果就是这个

3 dynamic images

现在我试图让用户上传多个新图像,但我希望他们能够预览新图像而不是动态图像。

我有多个预览的代码

<input id="galleryImgs" type="file" multiple="multiple" name="files[]"><button style="display: none;" onclick="reset2($('#galleryImgs'));event.preventDefault()"></button>
<div class="gallery"></div>

<script>
 $(function() {
  // Multiple images preview in browser
  var imagesPreview = function(input, editPostGalleryImgs) {

    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(editPostGalleryImgs);
            }

            reader.readAsDataURL(input.files[i]);
        }
    }

  };

  $('#galleryImgs').on('change', function() {
      imagesPreview(this, 'div.gallery');
  });

});
</script>

带回来了 dynamic images

问题是,我希望预览图像替换动态图像而不是显示在顶部。

1 个答案:

答案 0 :(得分:1)

使用replaceWith()

获得了我想要的结果

更改了此

imagesPreview(this, 'div.gallery');

到此

$(".imgFile").replaceWith(imagesPreview(this, 'div.gallery'));

现在它完美无缺!