开发者

jQuery or JavaScript: get MIME type of client file

I would like to detect the MIME type of a file on th开发者_如何学Pythone client side of my application using jQuery or JavaScript. Is there a way to do this? Thanks.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜