Sending image as binary via require(“http”) request to a remote server

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

I'm trying to send an image to remote server from nodejs server. 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

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(); });

Reference

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!