jQuery or JavaScript: get MIME type of client file jQuery or JavaScript: get MIME type of client file javascript javascript

jQuery or JavaScript: get MIME type of client file


You could use AJAX, make a HEAD request, and inspect the response headers for the Content-type header. But that only works if you're getting a file from a HTTP server.


To get the MIME type of a file chosen with an HTML file chooser, without submitting anything, try:

document.getElementById('fileChooserID').files[0].type // e.g. image/png

Example

http://jsbin.com/akati3/2

Try choosing an image, check the MIME type, and try to submit it. Then try something else that's not an image.


The only way to reliably detect a mime type is to parse the file on the server side, to confirm that it is the type that the user claims it to be, or that it fits a list of allowed types. Things to consider:

1 - JavaScript has limited access to the local filesystem, and with good reason.

2 - You cannot trust a mime type which has been received from a browser. It will not necessarily match the mime type of the sent file.

3 - In a situation where the user is allowed to upload files which fit a 'whitelist' of allowed types, validation is probably necessary anyway - considering that the application might have to actually do something with the file beyond storing them, which would at the very least involve parsing their headers for information such as run length (for a video) version number (for a Word document) and so on.


the idea IS NOT trust in the Browser..the idea is perform this validations on SERVER SIDE but, what a usefull thing if prior to send a 20MB file to the browser and next get rejected because a rule in the server...so, it is a good idea to "pre-check" if this file "is a candidate" to be uploaded, the final validation will be performed in the server.