When dealing with files in JavaScript, you may want to check whether or not a file is an image. This tutorial will show how to JavaScript check if file is image with pure JavaScript function and JQuery.
JavaScript
- Check if file is image regardless of its type
1 2 3 |
function isFileImage(file) { return file && file['type'].split('/')[0] === 'image'; } |
- Or If you want to target specific image types
1 2 3 4 5 |
function isFileImage(file) { const acceptedImageTypes = ['image/gif', 'image/jpeg', 'image/png']; return file && acceptedImageTypes.includes(file['type']) } |
JQuery
- Using JQuery to check if the file is an image
1 2 3 4 |
function isFileImage(file) { const acceptedImageTypes = ['image/gif', 'image/jpeg', 'image/png']; return file && $.inArray(file['type'], acceptedImageTypes) } |