Javascript Express:根据路径/文件设置内容类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7109732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Express: Setting content-type based on path/file?
提问by mahemoff
I know Express has the res.contentType() method, but how to set automatically content type based on path/file (including static content)?
我知道 Express 有 res.contentType() 方法,但是如何根据路径/文件(包括静态内容)自动设置内容类型?
采纳答案by Peter Lyons
Connectwill automatically set the content type, unless you explicitly set it yourself. Here's the snippet that does it. It uses mime.lookupand mime.charsets.lookup
Connect将自动设置内容类型,除非您自己明确设置。这是执行此操作的代码段。它使用mime.lookup和 mime.charsets.lookup
// mime type
type = mime.lookup(path);
//<SNIP>....
// header fields
if (!res.getHeader('content-type')) {
var charset = mime.charsets.lookup(type);
res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
}
If this isn't working for you, post your code as your custom code is likely interfering with the default behavior somehow.
如果这对您不起作用,请发布您的代码,因为您的自定义代码可能会以某种方式干扰默认行为。
回答by Andrei Neculau
Also, if you want to extend the mime-types that express(connect) knows about, you can do
另外,如果你想扩展 express(connect) 知道的 mime-types,你可以这样做
express.static.mime.define({'text/plain': ['md']});
or
或者
connect.static.mime.define({'text/plain': ['md']});
PS: the mime module is now located at https://github.com/broofa/node-mime
PS:mime 模块现在位于https://github.com/broofa/node-mime
回答by Michelle Tilley
The Express documentationshows that it can do this if you pass in the file name.
该Express文档表明,如果你在文件名通过它可以做到这一点。
var filename = 'path/to/image.png';
res.contentType(filename);
// Content-Type is now "image/png"
[Edit]
[编辑]
Here's an example which serves files from a relative directory called static
and automatically sets the content type based on the file served:
这是一个示例,它从名为的相对目录中提供文件,static
并根据所提供的文件自动设置内容类型:
var express = require('express');
var fs = require('fs');
var app = express.createServer();
app.get('/files/:file', function(req, res) {
// Note: should use a stream here, instead of fs.readFile
fs.readFile('./static/' + req.params.file, function(err, data) {
if(err) {
res.send("Oops! Couldn't find that file.");
} else {
// set the content type based on the file
res.contentType(req.params.file);
res.send(data);
}
res.end();
});
});
app.listen(3000);
回答by Tim Stewart
Express uses Connect, Connect uses Mime, and Mime includes the files mime.types(with default mime types from Apache) and node.types(with some further types contributed by node community). You could just customize one of these files within your copy of mime in node_modules to add your required content type, or Mime also has an API that lets you specify additional content-types or .types files to load from your code.
Express 使用 Connect,Connect 使用 Mime,Mime 包括文件mime.types(具有来自 Apache 的默认 mime 类型)和node.types(具有节点社区贡献的一些其他类型)。您可以在 node_modules 中的 mime 副本中自定义这些文件之一,以添加所需的内容类型,或者 Mime 也有一个 API,可让您指定要从代码加载的其他内容类型或 .types 文件。
回答by Abdennour TOUMI
Download this database(or Another link) : mime.types: , then
下载此数据库(或 其他链接):mime.types: ,然后
var db_mimes=[],mime_ext=''
$.get('mime.types',{},function(d){
var lines=d.split('\n').filter(function(e){ /* filter which starts with #*/})
lines.forEach(function(line){
mime_ext=line.split(' ')
mime_ext[1].split(' ').forEach(function(ext){
db_mimes.push({e:ext,m:mime_ext[0]})
});
//create object for each line . i.e: {mime:'',extension}
});
});
Then if you have fo example var fname="myfile.png"
那么如果你有例如 var fname="myfile.png"
var extension=fname.substr((~-this.lastIndexOf(".") >>> 0) + 2) // get extension from name
var minme=db_mimes.filter(function(el){return el.e === extension})[0]
回答by Abdennour TOUMI
Run the following cmd :
运行以下 cmd :
npm install xmimetype ;
Then , in your code :
然后,在您的代码中:
var xm=require("xmimetype");
xm.mimetypeOf("java");
xm.mimetypeOf("./lib/Person.java");
// -> text/x-java-source
xm.mimetypeOf("docx");
xm.mimetypeOf("./lib/overview.docx");
// -> application/vnd.openxmlformats-officedocument.wordprocessingml.document
For more info , check GIT repository.
有关更多信息,请查看GIT 存储库。
The opposite is available :
相反是可用的:
xm.extensionsOf("image/jpeg");
// -> [ 'jpeg', 'jpg', 'jpe' ]