当我查询这个问题时,我发现了很多帖子,但它们都是指如何将文件从浏览器上传到 node.js 服务器。我想将 node.js 代码中的文件上传到另一台服务器。我试图根据我对node.js的有限知识编写它,但它不起作用。
function (data) {
var reqdata = 'file='+data;
var request = http.request({
host : HOST_NAME,
port : HOST_PORT,
path : PATH,
method : 'POST',
headers : {
'Content-Type' : 'multipart/form-data',
'Content-Length' : reqdata.length
}
}, function (response) {
var data = '';
response.on('data', function(chunk) {
data += chunk.toString();
});
response.on('end', function() {
console.log(data);
});
});
request.write(reqdata+'\r\n\r\n');
request.end();
})
上述函数被其他生成数据的代码调用。
我尝试使用 curl -F "file=@
我收集了 tcpdump 数据并在wireshark 中进行了分析。从我的 node.js 代码发送的数据包缺少多部分数据所需的边界。我在 Wireshark 数据包中看到这条消息
The multipart dissector could not find the required boundary parameter.
知道如何在 node.js 代码中实现这一点吗?
最佳答案
jhcc's answer快到了。
为了在我们的测试中提供对此的支持,我对其进行了微调。
这是适合我们的修改版本:
var boundaryKey = Math.random().toString(16); // random string
request.setHeader('Content-Type', 'multipart/form-data; boundary="'+boundaryKey+'"');
// the header for the one and only part (need to use CRLF here)
request.write(
'--' + boundaryKey + '\r\n'
// use your file's mime type here, if known
+ 'Content-Type: application/octet-stream\r\n'
// "name" is the name of the form field
// "filename" is the name of the original file
+ 'Content-Disposition: form-data; name="my_file"; filename="my_file.bin"\r\n'
+ 'Content-Transfer-Encoding: binary\r\n\r\n'
);
fs.createReadStream('./my_file.bin', { bufferSize: 4 * 1024 })
.on('end', function() {
// mark the end of the one and only part
request.end('\r\n--' + boundaryKey + '--');
})
// set "end" to false in the options so .end() isn't called on the request
.pipe(request, { end: false }) // maybe write directly to the socket here?
变化是:
ReadableStream.pipe
returns the piped-to stream ,所以end
永远不会被调用。相反,在文件读取流上等待end
。request.end
将边界换行。
关于file-upload - 如何从 node.js 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5744990/