Using only JavaScript and framework like dojo/jQuery...
Is there a way to find the Content-Type for a particular file name extension?
Say if I type in the string "something.pdf", I want to show an alert that says "application/pdf"
or "something.html" show "text/html"?
MIME (Multipurpose Internet Mail Extensions) is an extension of the original Simple Mail Transport Protocol (SMTP) email protocol. It lets users exchange different kinds of data files, including audio, video, images and application programs, over email.
Whereas file extensions are commonly used for your OS to decide what program to open a file with, Mime types are used by your browser to decide how to present some data (or the server on how to interpret received data). Both are optional but it's a good practice to have an agreement.
I think you will need to maintain the mappings yourself (you could XHR a physical file and get it, but I doubt you want to do that)...
(function() {
var extToMimes = {
'img': 'image/jpeg',
'png': 'image/png',
...
}
window.getMimeByExt = function(ext) {
if (extToMimes.hasOwnProperty(ext)) {
return extToMimes[ext];
}
return false;
}
})();
jsFiddle.
This will return false
if it doesn't exist in your mapping. If you like, you could just return the extToMimes[ext]
, which will give undefined
if it doesn't exist. It also won't accidentally get things up the prototype chain.
There is also the option of accessing it if it is a file input
.
var mime = $('input[type="file"]').prop('files')[0].file;
Keep in mind the extension to mime type makes no guarantees about the actual file itself; you'd need to parse it server side to determine what kind of file it really is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With