Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load image from server that requires sending headers

I want to load an image from server that requires a token, but I don't know how to send the token in headers of axios or fetch request to get it loaded. How can I send headers with url to load my image from server in my React application?

Here is my image tag

<img 
   src={{
    uri: `${activeCoverHash}`,
    headers: { t: token }
   }} 
   alt={i.name}
   onLoad={() => console.log('___DONE___')}/>

but it gives me a 404 error. What can I do?

Actually I got that pattern from here, but it is only works on React Native not React.

like image 320
amdev Avatar asked Oct 21 '18 12:10

amdev


2 Answers

You can load the image by fetching the image using javascript and then loading it in the src attribute of image tag.

componentDidMount() {
    axios.get(`${activeCoverHash}`, { headers: {'t': token }, responseType: 'arraybuffer'}).then((res) => {

      let data = new Uint8Array(res.data);
      let raw = String.fromCharCode.apply(null, data);
      let base64 = btoa(raw);
      let src = "data:image;base64," + base64;

      this.img.src = src;
    });
  }

render() {
    return (
        <img src={""} alt={"Loading..."} ref={(e) => this.img = e} />
    )
}
like image 78
Prakash Sharma Avatar answered Nov 09 '22 08:11

Prakash Sharma


Using IONIC v4 and React would be:

import React from 'react';
import API from '../api';

type ImageWithAuthProps = {
    url: string;
}

const ImageWithAuth: React.FC<ImageWithAuthProps> = (props) => {

    // Components refs
    const img: React.Ref<HTMLImageElement> = React.createRef();

    // Load data
    React.useEffect(() => {
        API.get(`${props.url}`,
        {
            responseType: 'arraybuffer',
            headers: {
                'Accept': 'image/jpeg'
            }
        }).then((res) => {

            const blob = new Blob([res.data], {
                type: 'image/jpeg',
            });

            console.log("blob: ", blob);
            var objectURL = URL.createObjectURL(blob);
            if (img.current != null)
                img.current!.src = objectURL;
        });
    }, []);

    return (
        <img src={""} alt={"Loading..."} ref={img} />
    );

};

export default ImageWithAuth;
like image 21
Mariusz Wiazowski Avatar answered Nov 09 '22 08:11

Mariusz Wiazowski