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"?
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.
you can use node-mime
<script src="https://wzrd.in/standalone/mime@latest"></script>
<script>
mime.getType("something.pdf"); // etc.
<script>
https://wzrd.in/standalone/mime@latest is currently not available, so you have to use:
<script>
import mime from 'https://cdn.skypack.dev/mime';
console.log( mime.getType("file.jpg"));
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.