Created
August 21, 2022 06:59
-
-
Save kerolloz/960aab76213f4086ede6aaf3bb848609 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios, { AxiosError } from 'axios'; | |
import fs from 'fs'; | |
import formData from 'form-data'; | |
const imageUploaderKeyEnvVar = process.env['IMG_UPLOADER_KEY']; | |
export class ImageUploader { | |
static async upload(imagePath: string): Promise<string> { | |
const form = new formData(); | |
const image = fs.readFileSync(imagePath, { encoding: 'base64' }).toString(); | |
form.append('image', image); | |
try { | |
const res = await axios.post('https://api.imgbb.com/1/upload', form, { | |
headers: form.getHeaders(), | |
params: { key: imageUploaderKeyEnvVar }, | |
}); | |
return res.data.data.url; | |
} catch (error) { | |
const e = error as AxiosError; | |
console.error(e.response?.data); | |
throw new Error('Error uploading image'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment