NodeJS 从 HTTP 响应中读取文件附件

3

有人知道如何读取或访问HTTP响应的附件吗?

我的意思是,服务器响应是:

HTTP/1.1 200 OK
Server: something
Date: Fri, 01 May 2015 10:22:29 GMT
Content-Type: application/pdf
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Language, Cookie
X-Frame-Options: SAMEORIGIN
Content-Language: en
Content-Disposition: attachment; filename=mybill-234324.pdf
Set-Cookie: s=xxxxx; expires=Fri, 15-May-2015 10:22:29 GMT; httponly; Max-Age=1209600; Path=/; secure
Strict-Transport-Security: max-age=15552000

但是这个mybill-234324.pdf文件的内容在哪里呢?

我的代码:

var req = https.request({
    method: 'GET',
    host: 'thehost.ext',
    path: '/account/bills/' + number + '/',
    headers: {
      'Cookie': 's=supercryptedhash;',
      'Accept-Language': 'en-US,en'
    }
  }, function(res) {
    // ????
  });

  req.on('error', function(err) {
    console.error('Request Error', err);
  });

  req.end();

请提供代码示例。 - vanadium23
provided in question edit. - G. Ghez
尝试查看答案:https://dev59.com/CWIj5IYBdhLWcg3wilzB - vanadium23
使用“request”模块我无法安装,我需要一种基于“http”或“https”节点本机模块的解决方案。 - G. Ghez
你的响应处理程序在哪里?它将返回服务器上的所有内容,包括头信息和数据。 - Joe
2个回答

0

https文档(https://nodejs.org/api/https.html)提供了一个示例:

options = { ... };

var req = https.request(options, function(res) {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);

    res.on('data', function(data) {
        // var `data` is a chunk of data from the response body
        process.stdout.write(data);
    });
});


req.on('error', function(e) {
  console.error(e);
});

req.end();

我检查过了,但是当Content-Disposition头部为“attachment”时它没有起作用...让我再试一次看看。 - G. Ghez
е®ѓеғ”иҮӨд»Қ然еЏҮд»Өе·ӨдҢњгЂ‚httpе’ЊhttpsжЁҰеқ—еҮ№дғҺcontent-dispositionе¤өйѓЁжІҰжњ‰з»™дғ€з‰№е€«е…іжіЁгЂ‚ - Gabriel
这是什么意思,Gabriel?我不能在这种情况下下载,还是应该在读取响应正文时出现? - G. Ghez
你是想要实际下载文件吗?这里有一个完整的示例,演示如何将所有数据获取到一个字符串变量中 - https://gist.github.com/gmaybrun/fd35a06e6d0356aceef2。在`client.js`的`end`处理程序之后,您可以对该变量进行任何操作(例如,将其写入本地文件系统中的文件)。简而言之:node.js忽略了`content-disposition`头 - 它不会自动为您保存文件。它将内容数据传递给您的代码来处理,就像处理任何其他响应一样。 - Gabriel

0

我遇到了同样的问题,尝试了各种npm包来获取包含以下内容的文件的内容

content-disposition: Attachment

  const url = "https://XXXX"; // your URL Here
  const curl = require('curl');
  let options = {};  
  curl.get(url, options, function(err, response, body) {          
  console.log("BODY", body);      
  });

最终我使用 CURL 获取了响应


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接