简体   繁体   中英

How to Read image data from API and render in React Component

I am trying to render the image data from the Webservice and able to get the data like below

在此处输入图片说明

That image data i am trying read like the below but image is not displaying ,

getImageFromDrive = (path) => {
    let that = this;
    axios.get(Constants.API + Constants.Files, {
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            "Authorization": Constants.AUTH_Element + ',' + Constants.AUTH_ORG + ',' + Constants.AUTH_USER
        },
        params: {
            path: path
        }
    }).then(function (response) {
        var myThat =that;
        console.log(response);
        let data = response.data;
        var base64Flag = 'data:image/jpeg;base64,';
        var imageStr =
            that.arrayBufferToBase64(data.img.data.data);
        that.setState({img: base64Flag + imageStr});

    })
        .catch(function (error) {
            console.log(error);
        })
}
arrayBufferToBase64(buffer) {
    var binary = '';
    var bytes = [].slice.call(new Uint8Array(buffer));
    bytes.forEach((b) => binary += String.fromCharCode(b));
    return window.btoa(binary);
};

render() {
    const {img} = this.state;

    return (

        <img className="myImg" alt="" width="300"
             height="300"  src={img}/>
     )
    }

Can anyone suggest me how to read that kind of data and display

try below code.

export async function getImageData() {
        await axios.get(`your api url`, {responseType: 'arraybuffer'}).then((data) => {
            const b64Data = btoa(
                new Uint8Array(data.data).reduce(
                    (dataArray, byte) => {
                        return dataArray + String.fromCharCode(byte);
                    }, 
                    ''
                )
            );
            const userAvatarData = {
                key: 'userAvatar',
                value: `data:image/png;base64,${b64Data}`
            };
            return userAvatarData.value; // here we return the base64 image data to our component
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM