S
S
Sergey2021-08-06 16:56:56
Node.js
Sergey, 2021-08-06 16:56:56

How to implement sending an image to telegram without saving it locally?

Hello! I am new to Node.Js. How can I upload a photo using the /sendphoto method? On the server, I am accepting an image from the client's browser using "express-fileupload". How can I send a photo without saving it locally?
Here is a sample code.

function bufferToStream(myBuffer) {
    let stream = new Duplex();
    stream.push(myBuffer);
    stream.push(null);
    return stream;
}

router.post('/', (req, res) => {
    const fileBuffer = req.files.file.data;
    const mimetype = req.files.file.mimetype;

// Формирую тело запроса
    let body = boundaryMiddle+'Content-Disposition: form-data; name="chat_id"'+'\r\n\r\n'+ chat_id+'\r\n'+boundaryMiddle+'Content-Disposition: form-data; name="photo"; filename="blob"'+'\r\n'+'Content-Type: '+mimetype+'\r\n\r\n'+ bufferToStream(fileBuffer) +'\r\n'+boundaryLast;

    var options = {
        host: 'api.telegram.org',
        path: `/bot${token}/sendPhoto`,
        port: '443',
        method: 'POST',
        headers:{
            'Content-Type': `multipart/form-data; boundary=${boundary}`
        }
    };

    callback = function (response) {
        var str = ''
        response.on('data', function (chunk) {
            str += chunk;
        });

        response.on('end', function () {
            console.log(str);
        });
    }

    var request = https.request(options, callback);
    request.end(body);

In response to the request, I get: {"ok":false,"error_code":400,"description":"Bad Request: IMAGE_PROCESS_FAILED"}.
In fact, I think the error is due to the fact that I do not specify the Content-Length header. But I don't know how to specify the stream length?
Prompt in what direction to dig?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-08-06
@Alexandroppolus

Use https://www.npmjs.com/package/form-data to submit a multipart/form-data form

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question