javascript 在 Node.js 中,给定一个 URL,如何检查它是否是 jpg/png/gif?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8473703/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:33:40  来源:igfitidea点击:

In Node.js, given a URL, how do I check whether its a jpg/png/gif?

javascripthttpnode.jsmime-typescontent-type

提问by TIMEX

My current method is this:

我目前的方法是这样的:

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 ?????
    });
});

The image is obviously a picture, but node-mimesays it's application/octet-stream. Why?

图片明明是图片,node-mime却说是application/octet-stream。为什么?

Note: - I do not want to rely on the Response Headers content-type, because based on my experience, sometimes those response headers are set incorrectly...and they do not determine the true file type. (that's why I save it to a file, and then have node-mime determine it for me!)

注意: - 我不想依赖 Response Headers 内容类型,因为根据我的经验,有时这些响应头设置不正确......并且它们不能确定真实的文件类型。(这就是为什么我将它保存到一个文件中,然后让 node-mime 为我确定它的原因!)

I want to know the best way to determine if a file is an image, with 0 margin of error.

我想知道确定文件是否为图像的最佳方法,误差为 0。

Edit: I just realized that node-mime isn't "magic". It just checks for the extension :( ...

编辑:我刚刚意识到 node-mime 不是“魔法”。它只是检查扩展名:( ...

Edit2: I found this: https://github.com/SaltwaterC/mime-magic

Edit2:我发现了这个:https: //github.com/SaltwaterC/mime-magic

回答by rcode

Just read the first bytes of the stream, and check it for the so called "magic number".

只需读取流的第一个字节,并检查所谓的“幻数”。

Magic numbers are the first bits of a file which uniquely identify the type of file.

幻数是文件的第一位,用于唯一标识文件类型。

For example:
-Every JPEG file begins with ff d8(hex).
-Every png file begins with a 89 50 4e 47.
-There is a comprehensive table of magic numbers here

例如:-
每个 JPEG 文件都以ff d8(hex)开头。
- 每个 png 文件都以89 50 4e 47.
-there是幻数的综合表在这里

This way even if you have a file without extension you can still detect its type.
Hope this helps.

这样即使您有一个没有扩展名的文件,您仍然可以检测到它的类型。
希望这可以帮助。

回答by simonch

This code shows a working solution for the magic numbers approach (summary of the existing answers and information on https://github.com/request/request).

此代码显示了幻数方法的有效解决方案(https://github.com/request/request上现有答案和信息的摘要)。

var request = require('request');
var url = "http://www.somedomain.com/somepicture.jpg";
var magic = {
    jpg: 'ffd8ffe0',
    png: '89504e47',
    gif: '47494638'
};
var options = {
    method: 'GET',
    url: url,
    encoding: null // keeps the body as buffer
};

request(options, function (err, response, body) {
    if(!err && response.statusCode == 200){
        var magigNumberInBody = body.toString('hex',0,4);
        if (magigNumberInBody == magic.jpg || 
            magigNumberInBody == magic.png ||
            magigNumberInBody == magic.gif) {

            // do something

        }
    }
});

回答by alessioalex

There are two modules that can help you achieve this:

有两个模块可以帮助您实现这一目标:

https://github.com/SaltwaterC/mime-magic

https://github.com/SaltwaterC/mime-magic

https://github.com/bentomas/node-mime

https://github.com/bentomas/node-mime

回答by Sue Spence

In the intervening time since this question was first asked, mime-magic has become unsupported and its author recommends the use of mmmagic. I don't know what happened to node-mime, the link above is a 404. I found the following article which discusses the topic as well: https://nodejsmodules.org/tags/mime

自首次提出此问题以来的中间时间, mime-magic 已不受支持,其作者建议使用mmmagic。我不知道 node-mime 发生了什么,上面的链接是 404。我发现以下文章也讨论了该主题:https: //nodejsmodules.org/tags/mime

回答by bahri noredine

i developped this code and i test it and it work for me you can use it

我开发了这段代码并测试了它,它对我有用,你可以使用它

var express = require('express')
var app = express()
var http = require('http').Server(app).listen(80)
var upload = require('express-fileupload')
app.use(upload())
        app.get("/",(req,res)=>{
            res.sendFile(__dirname+"/file.html")
        })
app.post('/',(req,res)=>{
        var options = {
            method: 'GET',
            url: req.files.filename,
            encoding: null
        }
        if (req.files) {
         if (req.files.filename.data.toString('hex',0,4) ==  '89504e47' || req.files.filename.data.toString('hex',0,4) == 'ffd8ffe0' || req.files.filename.data.toString('hex',0,4) == '47494638' ) {
            var file = req.files.filename
            filename = file.name
            file.mv('./upload/'+filename,(err)=>{
               if (err) {
                   console.log('small err')
               } else {
                res.send('DONE')
               }
            })
         } else {
             console.log('it not an image')
         }
}
})