Search code examples
reactjstypescriptnext.jsimgur

How to add an uploaded image to my own ImgUr Album


I have created an application on ImgUr and recieved the ClientID and ClientSecret.

enter image description here

I know my album id for example: xbvhXo(not a real id)

I want to upload an image to my album.

What I have done:

I installed imgur npm package for my TypeScript Next.js project.

Here is the code for uploading images to ImgUr:

const albumID = 'xbvhXo';
const client = new ImgurClient({ 
    clientId: process.env.IMGUR_CLIENT_ID,
    clientSecret: process.env.IMGUR_CLIENT_SECRET,
 });
export async function uploadToImgUr(imgData: APImageData | Buffer[]): Promise<string[]> {
    let files: Buffer[];
    let album: string | undefined = albumID;
    let name: string | undefined;
    let title: string | undefined;
    let description: string | undefined;

    if(Array.isArray(imgData)) {
        files = imgData;
    } else {
        files = imgData.files;
        album = imgData.album ? imgData.album : albumID;
        name = imgData.name;
        title = imgData.title;
        description = imgData.description;
    }

    const uploadPromises = files.map(async (file) => {
        const response = await client.upload({
            image: file,
            type: 'stream',
            album: album,
            name: name,
            title: title,
            description: description,
        });

        return response.data.link;
    });

    return Promise.all(uploadPromises);
}

when trying to add the image to my Album, it errors out:

You are not the owner of album 'xbvhXo', which means you can't add images to it. For anonymous albums, use the album deletehash.

This is not true, as I am clearly the owner of this album.

How can I fix this?


Solution

  • Figured out that I need to

    1. call the ImgUr authorize endpoint with the client id and client secret to get refresh token and access token. ( This is a manual work, I access this [url](https://api.imgur.com/oauth2/authorize?client_id=response_type=token&state=, then manually clicked 'Allow'. It then redirected me to the callback url which I set up during the creation of my application in ImgUr Settings -> Application.

    2. Once got these 2 tokens, I added the following code:

      const client = new ImgurClient({ clientId: process.env.IMGUR_CLIENT_ID, clientSecret: process.env.IMGUR_CLIENT_SECRET, accessToken: process.env.IMGUR_ACCESS_TOKEN, refreshToken: process.env.IMGUR_REFRESH_TOKEN, });

    Then the rest code remains the same and it starts to working.