file upload: check if valid image

前端 未结 2 980
礼貌的吻别
礼貌的吻别 2020-12-18 01:30

I want to upload a file like this:


Is there any way to find out in javascript if the se

相关标签:
2条回答
  • 2020-12-18 01:58

    Firstly add accept="image/*" on your input, to accept only image files

    <input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/>
    

    Second, you can create image object to see if it is true image

    function validateAndUpload(input){
        var URL = window.URL || window.webkitURL;
        var file = input.files[0];
    
        if (file) {
            var image = new Image();
    
            image.onload = function() {
                if (this.width) {
                     console.log('Image has width, I think it is real image');
                     //TODO: upload to backend
                }
            };
    
            image.src = URL.createObjectURL(file);
        }
    };​
    
    0 讨论(0)
  • 2020-12-18 02:08

    Thank you Arūnas Smaliukas. Your answer got me close to what I wanted.

    Image.onload will only be called if the file is a valid image. So, it's not necessary to inspect this.width in the onload() call back.

    To detect that it is an invalid image, you can use Image.onerror.

    $().ready(function() {
      $('[type="file"]').change(function() {
        var fileInput = $(this);
        if (fileInput.length && fileInput[0].files && fileInput[0].files.length) {
          var url = window.URL || window.webkitURL;
          var image = new Image();
          image.onload = function() {
            alert('Valid Image');
          };
          image.onerror = function() {
            alert('Invalid image');
          };
          image.src = url.createObjectURL(fileInput[0].files[0]);
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="file" />

    0 讨论(0)
提交回复
热议问题