【问题标题】:request-promise : downloading/checking a file's MIME type?request-promise : 下载/检查文件的 MIME 类型?
【发布时间】:2016-12-23 10:40:47
【问题描述】:

使用标准请求模块,我们可以运行以下脚本来检查文件的 MIME 类型;

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 magicNumberInBody = body.toString('hex',0,4);
        if (magicNumberInBody == magic.jpg || 
            magicNumberInBody == magic.png ||
            magicNumberInBody == magic.gif) {
            console.log("It's an image!");
            return true;
        }
    }
});

这是不言自明的。但是,当使用 node.js 并依赖 Promises 时,我们如何执行上述操作?我尝试安装和使用request-promise,并编写了以下脚本;

return rp("http://www.somedomain.com/somepicture.jpg")
            .then((response) => {
                var magicNumberInBody = response.toString('hex',0,4);
                console.log(magicNumberInBody);
                if (magicNumberInBody == magic.jpg ||
                    magicNumberInBody == magic.png ||
                    magicNumberInBody == magic.gif) {
                    console.log("It's an image!");
                    return true;
                }

但是,对于不基于 html/txt 的任何内容,request-promise 似乎只返回原始二进制文件。

有谁知道我如何将上述数据更改为有意义的数据,我可以轻松地使用它来识别 MIME 类型是否为 jpg/png/gif?

【问题讨论】:

    标签: javascript node.js promise


    【解决方案1】:

    我先做一个头部请求

          // Download
          return Image._head($, $(image).attr('src'))
            .then((filename) => {
              return Image._download($, filename)
            })
            .then((code) => {
              return $
            })
    
    
      // Request
      Request.head(options)
        .then((data) => {
          console.log(data)
          // Get the content type
          // const type = data['content-type']
          // let ext = ''
    
          // // Extract extension
          // if (type === 'image/jpeg' || type === 'image/pjpeg') {
          //   ext = 'jpg'
          // } else if (type === 'image/png') {
          //   ext = 'png'
          // } else if (type === 'image/gif') {
          //   ext = 'gif'
          // }
    
          // Get filename
          let filename = null
          const disposition = data['content-disposition']
    
          if (disposition && disposition.indexOf('inline') !== -1) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
            var matches = filenameRegex.exec(disposition)
            if (matches != null && matches[1]) {
              filename = matches[1].replace(/['"]/g, '')
            }
          }
    
          // Path
          // const path = Path.join('./resources/images', `${filename}`)
    
          // console.log('content-type:', data.headers['content-type'])
          // console.log('content-length:', data.headers['content-length'])
          // console.log('content-disposition:', data.headers['content-disposition'])
          console.log('filename:', filename)
    
          // resolve(data.html)
          resolve(filename)
        })
        .catch((error) => {
          resolve(new Error(`${error} - Instagram - ${src}`))
        })
    

    然后是另一个实际下载文件的请求。

    希望这在某种程度上有所帮助

    【讨论】:

      【解决方案2】:

      您必须使用resolveWithFullResponse 选项:

      rp({
        uri: "http://www.somedomain.com/somepicture.jpg",
        resolveWithFullResponse: true
      }).then(res => {
        console.log(res.headers['content-type'])
      })
      

      【讨论】:

      • 谢谢,我从中获得了更多有用的数据,但仍然无法运行实际的上述脚本。 res.headers['content-type'] 只是返回图像的 "content-type': 'application/octet-stream"。我需要查看实际的 MIME 类型。
      • 抱歉,这完全是另一个问题,您无能为力,请参阅:stackoverflow.com/questions/9707204/…
      猜你喜欢
      • 2010-11-07
      • 2011-11-09
      • 1970-01-01
      • 2013-03-29
      • 2020-07-11
      • 1970-01-01
      • 2020-05-16
      • 2014-02-20
      • 1970-01-01
      相关资源
      最近更新 更多