skip to Main Content

I want to send an image with a Telegram message using ajax. I can send it ok using Postman and it gave me generated code to use with jQuery.

However I do not have a form to input the image. The image is instead in the same directory as the javascript file. I have tried just using the filename but I get a 400 Bad Request error.

        var message = `image caption`;

        var form = new FormData();
        form.append("photo", "image.png");
        form.append("chat_id", "xxxx");
        form.append("caption", message);

        var settings = {
            "async": true,
            "crossDomain": true,
            "url": "https://api.telegram.org/bot" + telegram_bot_id + "/sendPhoto",
            "method": "POST",
            "headers": {
              "Content-Type": "application/json",
              "cache-control": "no-cache"
            },
            "mimeType": "multipart/form-data",
            "processData": false,
            "data": form
        }

        $.ajax(settings).done(function (response) {
        console.log(response);
        });

2

Answers


  1. Just read the context of the image file and convert it to base64 and add it to your data as a string data

      let imgStr =  fs.readFileSync("Image File Path","utf-8");
      let imgBase64 = btoa(imgStr);
    
    Login or Signup to reply.
  2. You’re going to need a file input control to get access to any file on the client machine.

        <input id="the-file-input-id" type="file" name="photo"/>
    

    Also, some of the settings are incorrect

        var form = new FormData();
        var img = $('#the-file-input-id').prop('files')[0];
        form.append("photo", img);
        form.append("chat_id", "xxxx");
        form.append("caption", message);
    
        var settings = {
            "async": true,
            "crossDomain": true,
            "url": "https://api.telegram.org/bot" + telegram_bot_id + "/sendPhoto",
            "method": "POST",
            "headers": {
              //"Content-Type": "application/json", you are not sending json
              "cache-control": "no-cache"
            },
            //"mimeType": "multipart/form-data", this is not a real parameter
            "processData": false,
            "contentType": false,
            "data": form
        }
    
        $.ajax(settings).done(function (response) {
            console.log(response);
        });
    

    This should work assuming the api supports CORS.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search