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

前端 未结 7 1344
有刺的猬
有刺的猬 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 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');
    

提交回复
热议问题