如何在HTTP请求中发送缓冲区? [英] How do I send a buffer in an HTTP request?
问题描述
我在内存中有一个文件(缓冲区) - 文件系统上没有文件。
我想将该缓冲区发送到另一个谈论HTTP的服务器。
I have a file in memory (buffer) - there is no file on the file system. I want to send that buffer to another server that talks HTTP.
例如,某些API A 在内存中创建一个文件, SignServer 操纵此类文件,并使用新缓冲区进行响应。我的API从 A 获取文件并将其提供给SignServer。
For example, some API A creates a file in memory, SignServer manipulates such files, and responds with a new buffer. My API takes the file from A and feeds it to SignServer.
我尝试以多种方式将文件发送到SignServer,但它仍然响应状态为400(请求中缺少字段'data')。
I tried sending the file to SignServer in multiple ways, but it keeps responding with status 400 (missing field 'data' in request).
我尝试了什么:
var http = require('http');
var querystring = require('querystring');
var data = querystring.stringify({
workerName: 'PDFSigner',
data: file_buffer
});
var request = new http.ClientRequest({
hostname: 'localhost',
port: 8080,
path: '/signserver/process',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
// I also tried 'multipart/form-data'
'Content-Length': Buffer.byteLength(data)
}
});
request.end(data);
我尝试打印数据
,它显示:
workerName = PDFSigner& data =
workerName=PDFSigner&data=
哪个不好,因为 data
未设置为 file_buffer
。
我试过打印 file_buffer
,它确实有内容(不是null,不是未定义,实际上有里面的字节)。
因此字符串化缓冲区给出了一个空字符串。
Which is bad because data
wasn't set to file_buffer
.
I tried printing file_buffer
, and it does have content (not null, not undefined, actually has bytes inside).
So stringifying the buffer gave an empty string.
我尝试用 request 模块,它也不起作用。
I tried doing the same thing with the request module and it didn't work either.
请注意,SignServer不是在Node中编写的也不是JavaScript。它是一个Java应用程序,因此它可能不适用于json(这就是为什么我要尝试使用 querystring
)。是的,我尝试发送json。
Note that SignServer isn't written in Node nor JavaScript. It's a Java application, so it probably doesn't work with json (which is why I'm trying to do it with querystring
). Yes, I tried sending json.
推荐答案
数据
的原因是设置为空字符串在此问题和解决方案在此问题中给出。
The reason why data
is set to an empty string is described in this issue and the solution is given in this issue.
转义并对缓冲区进行字符串化,如下所示:
escape and stringify the buffer like so:
var data = querystring.stringify({
workerName: 'PDFSigner',
data: escape(file_buffer).toString('binary')
});
正如@robertklep所提到的,你的另一个问题是你无法使用<$发送一个大文件C $ C>应用程序/ x-WWW窗体-urlencoded 。你需要用 multipart / form-data
来做。
As @robertklep mentioned, your other problem is that you can't send a big file using application/x-www-form-urlencoded
. You'd need to do it with multipart/form-data
.
这篇关于如何在HTTP请求中发送缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!