Skip to content

Instantly share code, notes, and snippets.

@kerolloz
Created August 21, 2022 06:59
Show Gist options
  • Save kerolloz/960aab76213f4086ede6aaf3bb848609 to your computer and use it in GitHub Desktop.
Save kerolloz/960aab76213f4086ede6aaf3bb848609 to your computer and use it in GitHub Desktop.
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