Javascript 从httpResponse获取包含pdf的缓冲区,并将其用作附件

Javascript 从httpResponse获取包含pdf的缓冲区,并将其用作附件,javascript,node.js,pdf,parse-platform,sendgrid,Javascript,Node.js,Pdf,Parse Platform,Sendgrid,我正在尝试从包含pdf的远程url获取请求,并从其响应获取包含原始数据的缓冲区,并将其用作sendGrid的附件,但这似乎不起作用,因为发送的pdf是空的 下面查找我使用的代码段: Parse.Cloud.httpRequest({ url:"http://<MY_URL>/x.pdf", headers:{ "X-Parse-Application-Id":"<MY_ID>", "X-Parse-REST-API-Key": "&

我正在尝试从包含pdf的远程url获取请求,并从其响应获取包含原始数据的缓冲区,并将其用作sendGrid的附件,但这似乎不起作用,因为发送的pdf是空的

下面查找我使用的代码段:

Parse.Cloud.httpRequest({ url:"http://<MY_URL>/x.pdf",
    headers:{
        "X-Parse-Application-Id":"<MY_ID>",
        "X-Parse-REST-API-Key": "<MY_KEY>",
    } 
}).then(function(httpResponse) {
    //email.addFileFromBuffer('x.pdf', httpResponse.buffer); 
    //-- Doesn't work raise and exception
    email.addFileFromBuffer(request.params.toName+'_report.pdf', new Buffer(httpResponse.text));
    sendgrid.send(email).then(function() {
        response.success("Email sent!");
    }, function(e) {
        console.log(e);
        response.error("Uh oh, something went wrong with sending email");
    });
}, function(e) {
    console.log(e);
    response.error("Uh oh, something went wrong with pdf");
});
结果:

Ran cloud function sendEmail with:
Input: {"fileName":"x.pdf","toEmail":"xxx@gmail.com","toName":"XXX"}
Result: URIError: URI malformed
at encodeURIComponent (native)
at <anonymous>:325:38
at Parse.js:1:21050
at Array.forEach (native)
at Function.x.each.x.forEach (Parse.js:1:661)
at b._objectEach.b._each (Parse.js:1:21023)
at formEncode (<anonymous>:321:5)
at Object.Parse.Cloud.httpRequest (<anonymous>:532:24)
at SendGrid.send (sendgrid.js:292:19)
at main.js:29:12
httpRequest返回一个响应对象,该对象同时具有原始字节和字符串表示形式。您不需要创建新的缓冲区,只需使用response.buffer

挖掘它:

email.addFileFromBuffer(request.params.toName+'_report.pdf', httpResponse.buffer);

以下是获取缓冲区的方法:

Parse.Cloud.httpRequest('http://domain.net/assets/file.zip')
  .then(function(httpResponse) {
    httpResponse.buffer // <---- file contents here
  });

您不能使用二进制文件中的缓冲区,它应与此模块中的纯/文本一起使用。改为看一看。

当使用email.addFileFromBufferrequest.params.toName+''u report.pdf',httpResponse.buffer;结果例外。查看我的编辑1上更详细的跟踪。当您出现错误时,request.params.toName的内容是什么?我尝试了许多不同的名称,甚至作为常量。最简单的是xxx,因此输出应该是xxx_report.pdf。httpRequest调用是否返回有效的httpResponse?您收到一个格式错误的URI错误,我看到的唯一URI是您试图获取的文件的URI。从浏览器中呈现的url(因此来自get请求)将正确显示。记录的httpResponse是:I2015-05-18T20:41:56.281Z]{uuid:9b54ee70-9e37-55b9-4b26-4c8a2d182100,状态:200,标题:{接受范围:字节,内容长度:82545,内容类型:application/pdf,日期:2015年5月18日星期一20:41:56 GMT,Etag:\01f47c0487743af7838d76670539c9\,最后修改:2015年5月4日星期一次21:03:03 GMT},文本:%PDF-1.4\n%\n5 0对象\n流\nx]o0\u0014cWu\u0…已截断
Parse.Cloud.httpRequest('http://domain.net/assets/file.zip')
  .then(function(httpResponse) {
    httpResponse.buffer // <---- file contents here
  });