Javascript 在纯nodejs中上载多部分表单
我尝试了一些代码在基于节点的服务器上上传一个文件,但我遇到了一个套接字挂起错误 在谷歌搜索错误后,我看到一篇帖子,其中建议如果不调用request.end()会导致此错误,但正如您将看到的代码,我确实调用了request.end() 任何帮助、建议都将不胜感激Javascript 在纯nodejs中上载多部分表单,javascript,node.js,file-upload,Javascript,Node.js,File Upload,我尝试了一些代码在基于节点的服务器上上传一个文件,但我遇到了一个套接字挂起错误 在谷歌搜索错误后,我看到一篇帖子,其中建议如果不调用request.end()会导致此错误,但正如您将看到的代码,我确实调用了request.end() 任何帮助、建议都将不胜感激 var http = require('http'); var fs = require('fs'); var options = { hostname: 'api.built.io', port : 4
var http = require('http');
var fs = require('fs');
var options = {
hostname: 'api.built.io',
port : 443,
path : '/vi/uploads',
method : 'POST'
};
var request = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
var size;
fs.stat('/home/abhijeet/Downloads/fgo-2.jpg',function(err,stats){
size = stats.size;
console.log(size);
});
var boundaryKey = Math.random().toString(16); // random string
request.setHeader('Content-Type', 'multipart/form-data; boundary="'+boundaryKey+'"');
request.setHeader('application_api_key','1234');
request.setHeader('authtoken','123');
request.setHeader('Content-Length','42215');
// 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: image/jpeg\r\n'
// "name" is the name of the form field
// "filename" is the name of the original file
+ 'Content-Disposition: form-data; name="upload[upload]"; filename="/home/abhijeet/Downloads/fgo-2.jpg"\r\n'
+ 'Content-Transfer-Encoding: binary\r\n\r\n'
);
var readFile = fs.createReadStream('/home/abhijeet/Downloads/fgo-2.jpg', { bufferSize: 4 * 1024 })
.on('end', function() {
request.end('\r\n--' + boundaryKey + '--'); // mark the end of the one and only part
})
.pipe(request, { end: false }) // set "end" to false in the options so .end() isn't called on the request
request.on('error',function(error){
console.log(error);
});
// maybe write directly to the socket here?
request.end();
// console.log(readFile);
我发现了错误…这是由于添加了两次request.end()。谢谢大家您可能还想查看Yeah initial我使用了节点表单数据,但大幅增加了总体文件大小:您应该能够将
内容传输编码设置为二进制。它默认为base64,我相信这肯定会增加大小。