我目前的方法是这样的:
var request = require('request');
var mime = require('mime');
var fs = require('fs');
var uri = 'http://www.sweetslyrics.com/images/img_gal/25646_christina-perri-213968.jpg';
request({
'method':'GET',
'uri': uri
},function(err, response,body){
var tmp_path = '/tmp/123456';
fs.writeFile(tmp_path, body, function(err) {
console.log(mime.lookup(tmp_path)); //application/octet-stream ?????
});
});
图像显然是图片,但 node-mime
说它是 application/octet-stream
。为什么?
注意: - 我不想依赖响应 header 内容类型,因为根据我的经验,有时这些响应 header 设置不正确......并且它们不能确定真实的文件类型。 (这就是为什么我将它保存到一个文件中,然后让 node-mime 为我确定它!)
我想知道确定文件是否为图像的最佳方法,误差为 0。
编辑:我刚刚意识到 node-mime 不是“魔法”。它只是检查扩展名:( ...
Edit2:我发现了这个:https://github.com/SaltwaterC/mime-magic
最佳答案
只需读取流的第一个字节,并检查所谓的“魔数(Magic Number)”。
Magic numbers are the first bits of a file which uniquely identify the type of file.
例如:
- 每个 JPEG 文件都以 ff d8
(十六进制)开头。
- 每个 png 文件都以 89 50 4e 47
开头。
- 有一张综合的魔数(Magic Number)表here
这样,即使你有一个没有扩展名的文件,你仍然可以检测到它的类型。
希望这会有所帮助。
关于javascript - 在 Node.js 中,给定一个 URL,我如何检查它是否是 jpg/png/gif?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8473703/