How to check file MIME type with javascript before upload?

前端 未结 9 2224
挽巷
挽巷 2020-11-22 03:50

I have read this and this questions which seems to suggest that the file MIME type could be checked using javascript on client side. Now, I understand that the real validati

9条回答
  •  执念已碎
    2020-11-22 04:39

    Short answer is no.

    As you note the browsers derive type from the file extension. Mac preview also seems to run off the extension. I'm assuming its because its faster reading the file name contained in the pointer, rather than looking up and reading the file on disk.

    I made a copy of a jpg renamed with png.

    I was able to consistently get the following from both images in chrome (should work in modern browsers).

    ÿØÿàJFIFÿþ;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90

    Which you could hack out a String.indexOf('jpeg') check for image type.

    Here is a fiddle to explore http://jsfiddle.net/bamboo/jkZ2v/1/

    The ambigious line I forgot to comment in the example

    console.log( /^(.*)$/m.exec(window.atob( image.src.split(',')[1] )) );

    • Splits the base64 encoded img data, leaving on the image
    • Base64 decodes the image
    • Matches only the first line of the image data

    The fiddle code uses base64 decode which wont work in IE9, I did find a nice example using VB script that works in IE http://blog.nihilogic.dk/2008/08/imageinfo-reading-image-metadata-with.html

    The code to load the image was taken from Joel Vardy, who is doing some cool image canvas resizing client side before uploading which may be of interest https://joelvardy.com/writing/javascript-image-upload

提交回复
热议问题