Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

javascript - file upload: check if valid image

I want to upload a file like this:

<input type="file" name="uploadPicture"/>

Is there any way to find out in javascript if the selected file is a valid image?

I know that I can check the file extension. The problem with that is someone can change a .txt file to .jpg and it would pass the validation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...