jQuery how to check if uploaded file is an image without checking extensions?

前端 未结 7 1269
有刺的猬
有刺的猬 2021-01-31 09:17

Newbie here. The problem is that I currently have written a method which checks uploaded file size and extension in order to validate it. However, checking extensions is not a s

相关标签:
7条回答
  • 2021-01-31 09:54

    What I want to do is to check the actual file type

    Try accessing files[0].type property . See Using files from web applications

    $(":file").on("change", function(e) {
    
      console.log(this.files[0].type);
      
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input type='file' id='imageLoader' name='imageLoader' accept="image/*" data-type='image' />

    0 讨论(0)
  • 2021-01-31 09:54

    If anyone comes here who is using jQuery Validator, a simple method would be:

    jQuery.validator.addMethod(
        "onlyimages",
        function (value, element) {
            if (this.optional(element) || !element.files || !element.files[0]) {
                return true;
            } else {
                var fileType = element.files[0].type;
                var isImage = /^(image)\//i.test(fileType);
                return isImage;
            }
        },
        'Sorry, we can only accept image files.'
    );
    

    which is then added to the .validate() function.

    0 讨论(0)
  • 2021-01-31 09:59

    Pls refer a related query here. The answer here suggests to load the image in an Image object and check for it's width and height properties to be non zero. I think the technique can be used to solve your problem too.

    I also worked out a fiddle for you to refer. Pertinent code below:

    var img = new Image();
    img.addEventListener("load",function(){
      alert('success');
    });
    img.addEventListener("error",function(){
          alert('error');
    });
      img.src = picFile.result; 
    
    0 讨论(0)
  • 2021-01-31 10:01

    You don't need jquery here.

    var mimeType=this.files[0]['type'];//mimeType=image/jpeg or application/pdf etc...
    
    
    //ie image/jpeg will be ['image','jpeg'] and we keep the first value
        if(mimeType.split('/')[0] === 'image'){
           console.log('the file is image');
        }
    

    You can also create a function to check when a file is image.

    function isImage(file){
       return file['type'].split('/')[0]=='image');//returns true or false
    }
    
     isImage(this.file[0]);
    

    Update (es6)

    using es6 includes method, makes it even more simple.

    const isImage = (file) => file['type'].includes('image');
    
    0 讨论(0)
  • 2021-01-31 10:02

    You could try to convert file type in string and after that slice this string like that:

    if(String(file.type).slice(0, 6) === 'image/') {....some code}
    
    0 讨论(0)
  • 2021-01-31 10:04

    Try something like this:

    JavaScript

    const file = this.files[0];
    const  fileType = file['type'];
    const validImageTypes = ['image/gif', 'image/jpeg', 'image/png'];
    if (!validImageTypes.includes(fileType)) {
        // invalid file type code goes here.
    }
    

    jQuery

    var file = this.files[0];
    var fileType = file["type"];
    var validImageTypes = ["image/gif", "image/jpeg", "image/png"];
    if ($.inArray(fileType, validImageTypes) < 0) {
         // invalid file type code goes here.
    }
    
    0 讨论(0)
提交回复
热议问题