skip to Main Content

I am trying to send a image from the internet to an API using multipart/form-data.

I was able to do this by saving the image in a temp folder using request.pipe(fs.createWriteStream) and upload using fs.createReadStream

But how can i do this without saving it in a temp folder?

I tried creating a new request and sending the body as a new Buffer but didn’t work.

Extra information:

I am implementing the Telegram Bot API method sendPhoto:
https://core.telegram.org/bots/api#sendphoto

I am using the request module for the integration:
https://github.com/request/request

Thanks.

2

Answers


  1. With the request node library, you can get binary content from the resource setting encoding: null in requestSettings. So the binary content is stored in memory into an object (Buffer).

    To send a photo using the node-telegram-bot, you will do:

    var TelegramBot = require('node-telegram-bot-api');
    var bot = new TelegramBot(token);
    
    var requestSettings = {
        url: 'http://httpbin.org/image',
        encoding: null
    };
    
    request(requestSettings, function (error, response, buffer) {
        if (!error && response.statusCode == 200) {
            bot.sendPhoto(chatId, buffer)
        }
    });
    
    Login or Signup to reply.
  2. I Had the same problem and I resolved with the next code, using the request-promise library

        const rp = require('request-promise');
    
        const req = {
            'url': 'https://store.server.com',
            'json': true,
            'resolveWithFullResponse': true
        };
    
        req['formData'] = {
            media: rp.get('https://videourl.com')
        };
        return rp.post(req)
            .then(response => return response)
            .catch(error => return throw error);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search