Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 请求承诺:下载/检查文件';什么是MIME类型?_Javascript_Node.js_Promise - Fatal编程技术网

Javascript 请求承诺:下载/检查文件';什么是MIME类型?

Javascript 请求承诺:下载/检查文件';什么是MIME类型?,javascript,node.js,promise,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,

使用标准请求模块,我们可以运行以下脚本来检查文件的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并依赖承诺时,我们如何执行上述操作?我已尝试安装和使用,并编写了以下脚本

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?

您必须使用
resolveWithFullResponse
选项:

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

您必须使用
resolveWithFullResponse
选项:

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

我先做一个头部请求

      // 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}`))
    })
然后是另一个实际下载文件的请求


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

我先做一个head请求

      // 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}`))
    })
然后是另一个实际下载文件的请求


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

谢谢,我从中获得了更多有用的数据,但仍然无法运行实际的上述脚本。res.headers['content-type']只返回图像的“content-type”:“application/octet stream”。我需要查看实际的MIME类型。对不起,巴德,这是另一个问题,您对此无能为力,请参阅:谢谢,我从中获得了更多可用数据,但仍然无法运行实际的上述脚本。res.headers['content-type']只返回图像的“content-type”:“application/octet stream”。我需要查看实际的MIME类型。对不起,巴德,这是另一个问题,您对此无能为力,请参阅: