Home > Blockchain >  How to write an image file downloaded from telegram api
How to write an image file downloaded from telegram api

Time:02-02

Im doing a request from my express server: const photo = await axios.get(https://api.telegram.org/file/bot${BOT_TOKEN}/photos/file_0.jpg) and getting file data like this: data: '����\x00\x10JFIF\x00\x01\x01\x01\x00\x00\x00\x00��\x00C\x00\x04\x03\x03\x04\x03\x03\x04\x04\x03\x04\x05\x04\x04\x05\x06\n' '\x07\x06\x06\x06\x06\r\t\n' '\b\n' ...'

How should I write this data to file on server?

I tried do this with buffer like this: const buff = Buffer.from(photo.data) fs.writeFile('./images/newFile.jpg', buff, (e) => { console.log(e) }) but it doesn't work. What am i doing wrong?

CodePudding user response:

here you are

const Fs = require('fs')  
const Path = require('path')  
const Axios = require('axios')
const BOT_TOKEN = "something to be changed"
/**
 * function to download a file using axios 
 * @param {string} url the url you need to download the file / image
 * @param {string} filename optional file name to be saved on the disk  
 * @returns promise resolved if downloading finished rejected if download failed
 */
async function download (url, filename) {  
    // to join the path correctly 
  const path = Path.resolve(__dirname, filename ? filename : 'image.jpg')
  const writer = Fs.createWriteStream(path)

  const response = await Axios({
    url,
    method: 'GET',
    responseType: 'stream'
  })

  response.data.pipe(writer)

  return new Promise((resolve, reject) => {
    writer.on('finish', resolve)
    writer.on('error', reject)
  })
}

download('https://api.telegram.org/file/bot${BOT_TOKEN}/photos/file_0.jpg', 'image.jpg')

  • Related