[英]Sending image as binary via require(“http”) request to a remote server
I'm trying to send an image to remote server from nodejs server. 我正在尝试从nodejs服务器向远程服务器发送图像。 Here's the request format so far.
这是迄今为止的请求格式。
Note: Just like binary request in postman and choosing a file and sending) 注意:就像邮递员中的二进制请求并选择文件并发送一样)
function upload(options, body) {
body = body || '';
return new Promise(function(resolve, reject){
const https = require('https');
https.request(options, function(response) {
var body = [];
response.on('data', function(chunk) {
body.push(chunk);
});
response.on('end', function(){
resolve(JSON.parse(Buffer.concat(body).toString()))
});
}).on('error', function(error) {
reject(error);
}).end(body);
});
}
Use: 采用:
var options = {
hostname: "hostname",
path: "/upload",
port: 443,
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'image/png'
}
};
fs.readFile('./img/thumbnail.png', function(error, data) {
options.body = data;
upload(options).then(...
});
Edit 2 编辑2
After several attempts, came across an efficient strategy to upload images via streams, here's how it looks like but still not success. 经过几次尝试,遇到了一个通过流上传图像的有效策略,这是它的样子但仍然没有成功。
const https = require('https');
var request = https.request(options, function(response) {
var buffers = [];
response.on('data', function(chunk) {
buffers.push(chunk);
});
response.on('end', function(){
console.log(response.headers['content-type']);
var body = JSON.parse(buffers.length ? Buffer.concat(buffers).toString() : '""');
response.statusCode >= 200 && response.statusCode < 300 ? resolve(body) : reject(body);
});
}).on('error', function(error) {
reject(error);
});
const fs = require('fs');
var readStream = fs.ReadStream(body.path);
readStream.pipe(request);
readStream.on('close', function(){
request.end();
});
I think you just want this: 我想你只想要这个:
fs.createReadStream('./img/thumbnail.png').pipe(https.request({
hostname: 'hostname',
path: '/upload',
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'image/png',
}
}, function (response) { ... }));
The issue with your code is that you were putting the body into options.body
, but per the documentation , it doesn't look like there is any such option. 您的代码的问题在于您将正文放入
options.body
,但根据文档 ,它看起来不像是有任何此类选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.