user7915134
user7915134

Reputation:

File upload/preview and unable to change dimensions of image

I am trying to upload an image and preview it before a user submits it but for some reason I am unable to change the width or height of either the div or image and it previews at it's normal dimensions. I even set it at 1px by 1px and it still doesn't work.

$(function() {
    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);
                 }

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

          $('#upload-image').on('change', function() {
              imagesPreview(this, 'img.image');
       });
   });
div.img_container {
    max-width: 1px;
    max-height: 1px;
}
img.image {
    width: 1px;
    height: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action='upload.php' method='post' enctype='multipart/form-data'>
   <input id='upload-image' type='file' name='files[]' multiple>
   <input type='submit' value='Upload'>
</form>
<div class='img_container'><img class='image'></div>

Upvotes: 1

Views: 590

Answers (2)

Max Martynov
Max Martynov

Reputation: 739

@Kosh Very was first here :)

I advice you check the code in the inspector next time.

enter image description here

Upvotes: 0

Kosh
Kosh

Reputation: 18393

You're appending image into image instead of updating its src:

$(function() {
  var imagesPreview = function(input, img) {

    if (input.files) {
      var filesAmount = input.files.length;

      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();

        reader.onload = function(event) {
          $(img).attr('src', event.target.result)
        }

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

  };

  $('#upload-image').on('change', function() {
    imagesPreview(this, 'img.image');
  });
});
img.image {
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action='upload.php' method='post' enctype='multipart/form-data'>
  <input id='upload-image' type='file' name='files[]' multiple>
  <input type='submit' value='Upload'>
</form>
<div class='img_container'><img class='image'></div>

Upvotes: 2

Related Questions