Engineer bro!
Fri Mar 04 2022 (2 years ago)
Engineer by mistake!
I am a software engineer by passion
Almost all applications either small or big needs some sort of service to host the image. Imgur is one of those services that provide image hosting for free. We can also use its API to programmatically upload the images. In this article, we'll see how can we upload the image programmatically using Imgur APIs.
Imgur is paid and free also, for more information you can go https://rapidapi.com/imgur/api/imgur-9/pricing
In order to use the APIs of Imgur, we need their API credentials.
The first step in this process is signup. Once you signup, then you can go to https://imgur.com/account/settings/apps and copy Client ID
.
Now you have Client ID
and NodeJs installed, we can use this to access the API of Imgur.
export function uploadImage(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, { encoding: "base64" }, (err, data) => {
if (err) {
reject(err);
return;
}
const options = {
method: "POST",
url: "https://api.imgur.com/3/image",
headers: {
authorization: "Client-ID ....",
},
data: {
image: data,
},
};
axios
.request(options)
.then(function (response) {
resolve(response.data);
})
.catch(function (error) {
reject(error.response.data);
});
});
});
}
uploadImage("./img.png")
.then((res) => console.log(res))
.catch((err) => console.log(err));
You can use the above function in NodeJs to read the local image file and upload it on Imgur. We need to send the file in base64
format. So, encode the data into base64
format before uploading.
If you know any better service, then you can suggest in the comments below.
© 2021 dsabyte. All rights reserved