Skip to content

Instantly share code, notes, and snippets.

@bilal-08
Last active December 15, 2022 17:08
Show Gist options
  • Save bilal-08/8e6740139db3495c8f80ea01587309cd to your computer and use it in GitHub Desktop.
Save bilal-08/8e6740139db3495c8f80ea01587309cd to your computer and use it in GitHub Desktop.
How to upload/post image using node-fetch
import FromData from 'form-data'; // form-data depcrecated use alternative, works for now
import fetch from 'node-fetch';
import * as ft from 'file-type'; // for detecting extention of the file from the buffer
const url = 'https://i.waifu.pics/1y5O6HN.jpg'; // example link
const getbuffer = async (url)=> await fetch(url).then(x =>x.buffer());
async function upload(){
const buffer = await getbuffer(url)
const {ext} = await ft.fileTypeFromBuffer(buffer)
console.log('extention is ',ext);
let form = new FromData()
form.append('file-name',buffer,'tmp.'+ext); // form to post it on request
const res = await fetch('https://telegra.ph/upload', { //telegraph a free site to upload stuff, can use any other like imgbb.com but you should see what they requires in thier header
method: 'POST',
body: form
})
const image = await res.json()
console.log(image[0].src,'image url')
const src = `http://telegra.ph/${image[0].src}`
console.log(src) // uploaded image
}
upload();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment