Skip to content
Advertisement

Show a preview picture using JavaScript before uploading files

I have a little script for uploading images with PHP and showing a preview picture before click “upload”. It uses an input “multiple” for upload multiple files… So done, it works fine, but I have a little problem …

When I duplicate the input type="file" (and erase Multiple) with two, three or more inputs, PHP processes the uploaded files but JavaScript shows the first picture only …

How can I show a picture for all the inputs?

This is my script :

index.php

    <?php include("file-upload.php"); ?>

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

  <title>PHP 7 Upload Multiple Files Example</title>
  <style>
    .container {
      max-width: 450px;
    }
    .imgGallery img {
      padding: 8px;
      max-width: 100px;
    }    
  </style>
</head>

<body>

  <div class="container mt-5">
    <form action="" method="post" enctype="multipart/form-data" class="mb-3">
      <h3 class="text-center mb-5">Upload Multiple Images in PHP 7</h3>

      <div class="user-image mb-3 text-center">
        <div class="imgGallery"> 
          <!-- Image preview -->
        </div>
      </div>

      <div class="custom-file">
        <input type="file" name="fileUpload[]" class="custom-file-input" id="chooseFile" multiple>
        <label class="custom-file-label" for="chooseFile">Select file</label>
      </div>

      <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
        Upload Files
      </button>
    </form>

    <!-- Display response messages -->
    <?php if(!empty($response)) {?>
        <div class="alert <?php echo $response["status"]; ?>">
           <?php echo $response["message"]; ?>
        </div>
    <?php }?>
  </div>

  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

  <script>
    $(function() {
    // Multiple images preview with JavaScript
    var multiImgPreview = function(input, imgPreviewPlaceholder) {

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

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

    };

      $('#chooseFile').on('change', function() {
        multiImgPreview(this, 'div.imgGallery');
      });
    });    
  </script>
</body>
</html>

Advertisement

Answer

The #chooseFile CSS selector selects by ID – that’s what the # does. IDs must be unique in HTML (obviously, because the whole point of an ID is to uniquely identify something). So to make that select several input elements, you’d be best to use a class instead as the selector.

For example:

$(function() {
  // Multiple images preview with JavaScript
  var multiImgPreview = function(input, imgPreviewPlaceholder) {

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

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

  };

  $('.chooseFile').on('change', function() {
    console.log("detected change");
    multiImgPreview(this, 'div.imgGallery');
  });
});
.imgGallery img {
  padding: 8px;
  max-width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="custom-file">
  <input type="file" name="fileUpload[]" class="custom-file-input chooseFile">
  <label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<div class="custom-file">
  <input type="file" name="fileUpload[]" class="custom-file-input chooseFile">
  <label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<div class="custom-file">
  <input type="file" name="fileUpload[]" class="custom-file-input chooseFile">
  <label class="custom-file-label" for="chooseFile">Select file</label>
</div>

<div class="imgGallery">
  <!-- Image preview -->
</div>

You might find jQuery’s documentation about selectors is useful background reading: https://api.jquery.com/category/selectors/

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement