0

I am trying to upload a file using request module to Telegram's Bot API. However, I end up with a 502 Gateway Error. Here's my code:

var request = require("request");
var fs = require("fs");
fs.readFile("image.png",function(err,data){
    var formdata = {};
    formdata.chat_id = <chatid>;
    formdata.photo = data;
    if(err)
      console.log(err);
    request({
      url : "https://api.telegram.org/bot<token>/sendPhoto",
      method : "POST",
      headers : {
        "Content-Type" : "multipart/form-data"
      },
      formData : formdata
    },function(err,res,body){
        if(err)
          console.log(err)
        console.log(body);
    })
});

Is this the proper way to upload a file or am I making a mistake somewhere?

An SO User
  • 24,612
  • 35
  • 133
  • 221

1 Answers1

1

I suggest, it's better for you to use form field of request object, which gives you possibility to send file using createReadStream function of fs module.For example:

var r = request.post({
        url: url
      },someHandler);

var form = r.form();
form.append('file',fs.createReadStream(filePath));

For proper use read:

https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options https://github.com/request/request#forms

  • Worked! What's the difference between your code and mine? – An SO User Jul 02 '15 at 19:07
  • 1
    For advanced cases, you can access the form-data object itself via r.form(). This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling form() will clear the currently set form data for that request.) - cite from https://github.com/request/request#forms Main idea is - `form()` clears form data, and this usage sets proper headers(multipart/form-data, content-length,content-type,etc.) and it can recognize and fetch all the required information from common types of streams (fs.readStream, http.response) – Rostislav Volskyi Jul 02 '15 at 19:18