request-promise:下载/检查文件的MIME类型?

时间:2016-08-16 22:16:16

标签: javascript node.js promise

使用标准请求模块,我们可以运行以下脚本来检查文件的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的内容,请求承诺似乎只返回原始二进制文件。

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

2 个答案:

答案 0 :(得分:2)

您必须使用resolveWithFullResponse选项:

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

答案 1 :(得分:0)

我先做头部请求

      // 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}`))
    })

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

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