文件上传/预览,无法更改图像尺寸

时间:2018-07-22 19:59:03

标签: javascript jquery html css file-upload

我正在尝试上传图像并在用户提交图像之前对其进行预览,但是由于某些原因,我无法更改div或图像的宽度或高度,并且无法以其正常尺寸进行预览。我什至将其设置为1px x 1px,但仍然无效。

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

2 个答案:

答案 0 :(得分:3)

您要将图像添加到图像中,而不是更新其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>

答案 1 :(得分:1)

@Kosh Very首先是在这里:)

我建议您下次在检查器中检查代码。

enter image description here