m-inan / react-upload-gallery

React for Upload Image Gallery. Sorted by drag & drop and Customizable
MIT License
80 stars 44 forks source link

Adding Custom Headers for Image Requests with Bearer Token Authentication #40

Open msiemaszko opened 9 months ago

msiemaszko commented 9 months ago

Hi! Is it possible to add a custom header to the request that downloads images from the API? My server requires a bearer token for every image request. I have no idea myself.

E: headers prop is effective only for upload request. I don't know how to inject own http client, or provide images in other ways.

msiemaszko commented 9 months ago

I figured out how to replace the image source with the blob URL.

        const action={`${process.env.REACT_APP_API_URL}/protocols/${id}/photos`}

        <RUG
            onSuccess={(response) => replaceSourceWithBlob(response)}
            action={action}
            ...

and after

    const replaceSourceWithBlob = (image) => {
        api.get(image.source, {
            responseType: 'blob',
            headers: {
                Authorization: `Bearer ${getToken()}`
            }
        }).then((response) => {
            const url = URL.createObjectURL(response.data);
            image.source = url;
            setDummyState(url); // anything make it rerender
        });

        return null;
    }

But I'm not proud of this code. I would appreciate better direction.