首页 > 解决方案 > 在上传替换最后一个图像问题之前上传和预览文件

问题描述

我正在尝试上传图像并一张一张预览它,但它会替换最后一张图像。我想继续添加越来越多的图像,但只有最后一张图像显示在收到的 $_FILES 数组中

保持所有上传图像的形式并保持预览。

我的代码

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
    <input type="file" id="add-gallary" name="filecollections[]">
        <input type="submit" value="Submit">
        
    <div class="gallery"></div>

</form> 
<script>
$(function() {
var upload_count = 0;
    
    var imagesPreview = function(input, placeToInsertImagePreview) {

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

                // input.files.append(input.files[i]);


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

    };

    $('#add-gallary').on('change', function() {
        imagesPreview(this, 'div.gallery');
    });
});
</script>

标签: javascriptjquery

解决方案


仅上传最后一张图片的原因是您将图片存储在一个文件中,array因为您有单个文件上传input

如果你想上传多张图片,你在表单提交上有预览器,你需要将它们存储在我命名的数组中imagesToUpload

一旦您预览了所有图像并准备提交带有您选择和预览的图像的表单,您就可以forEach遍历该数组imagesToUpload并将这些文件数据附加到formData.

然后,您将这个 formData 到您的后端,并使用ajax请求将所有图像上传到后端。

运行下面的代码片段以查看该数组正在使用.push函数来存储您预览的所有图像。

$(function() {
  var upload_count = 0;

  //Store images in array
  var imagesToUpload = []

  var imagesPreview = function(input, placeToInsertImagePreview) {

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

        // input.files.append(input.files[i]);

        //Push images to array on preview                
        imagesToUpload.push(input.files[i])


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

  };

  $('#add-gallary').on('change', function() {
    imagesPreview(this, 'div.gallery');
    console.log(imagesToUpload)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
  <input type="file" id="add-gallary" name="filecollections[]">
  <input type="submit" value="Submit">

  <div class="gallery"></div>

</form>


推荐阅读