I’m working on a web application where users can upload images through an HTML form. The images get converted to base64 format automatically. Now I need to send these base64 encoded photos through a Telegram bot using JavaScript and jQuery.
I’ve tried several approaches but keep running into issues with the base64 format. The regular photo sending methods don’t seem to work with base64 data. Has anyone successfully implemented this? What’s the proper way to handle base64 image data when using Telegram’s bot API?
Here’s a basic example of what I’m trying to achieve:
function transmitImageToBot(base64Data, chatId) {
const botToken = 'YOUR_BOT_TOKEN';
const apiUrl = `https://api.telegram.org/bot${botToken}/sendPhoto`;
$.ajax({
url: apiUrl,
method: 'POST',
data: {
chat_id: chatId,
photo: base64Data // This doesn't work
},
success: function(response) {
console.log('Image sent successfully');
}
});
}
Same headache here. Make sure you’re setting the MIME type correctly when creating the blob - Telegram’s really picky about image formats. Also double-check your base64 string isn’t getting corrupted during upload. Special characters often get mangled in form submissions and break the conversion.
Telegram’s sendPhoto endpoint won’t accept raw base64 data - it needs either a file upload or URL. You’ve got to convert that base64 string to a file blob first. Here’s what fixed it for me:
function base64ToBlob(base64Data) {
const byteCharacters = atob(base64Data.split(‘,’)[1]);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
return new Blob([byteArray], {type: ‘image/jpeg’});
}
Hit this same issue last month building a photo sharing feature. The Blob approach works, but there’s a simpler route depending on your setup - use the InputFile interface with a Buffer. Skip the Blob conversion and create a Buffer straight from the base64 data, then send it as binary. Cuts through some FormData headaches: function sendBase64Photo(base64Data, chatId) { const botToken = ‘YOUR_BOT_TOKEN’; const base64Image = base64Data.replace(/^data:image/[a-z]+;base64,/, ‘’); const buffer = Buffer.from(base64Image, ‘base64’); const formData = new FormData(); formData.append(‘chat_id’, chatId); formData.append(‘photo’, new Blob([buffer]), ‘photo.jpg’); return fetch(https://api.telegram.org/bot${botToken}/sendPhoto, { method: ‘POST’, body: formData }); } Watch out for Telegram’s 10MB photo limit. Also make sure you strip the data URL prefix properly - if you don’t, the base64 decode fails silently.