简体   繁体   中英

How can I display a jpeg stream as an image?

I've got an API with authentication, because of that I can't just use a normal <img> Tag like <img src="https://some-link.com/image.jpeg" /> .

Because I have to authenticate I'm using axios to make my call to the API:

const instance =  axios.create({
    headers: {
        'Accept': 'image/jpeg',
        'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxx'
    }
})
function  find() {
    return instance.get('https://server.com/instances/955a3576/preview');
}

I'm now getting my Image as a jpeg stream looking similar like this (I've only pasted a little part of the whole response data):

����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C\u0000\u0003\u0002\u0002\u0003\u0002\u0002\u0003\u0003\u0003\u0003\u0004\u0003\u0003\u0004\u0005\b\u0005\u0005\u0004\u0004\u0005\n\u0007\u0007\u0006\b\f\n\f\f\u000b\n\u000b\u000b\r\u000e\u0012\u0010\r\u000e\u0011\u000e\u000b\u000b\u0010\u0016\u0010\u0011\u0013\u0014\u0015\u0015\u0015\f\u000f\u0017\u0018\u0016\u0014\u0018\u0012\u0014\u0015\u00

How can I display this kind of response as an image on my website? I'm using ReactJS, maybe there is a component for React to do this (Unfourtunately I couldn't find one)?

Thanks for any help.


Update: Thanks you dune184 for the suggestion with the Blobs. This seems promising.

I've created a Blob with following function:

this.setState({myImage: new Blob([res.data], { type: 'image/jfif' })});

Now I'm trying to display the image like this:

<img src={this.state.myImage ? URL.createObjectURL(this.state.myImage) : null}></img>

But the image isn't displaying. Any suggestion what I'm doing wrong?

Thank you for your suggestions. I could now solve my issue with the Blob as suggested by dune184.

I switched from axios to fetch, which can easly create and return a Blob Object:

function  find(id) {
    var url = 'https://server.com/instances/'+ id +'/preview';
    return fetch(url, {
        method: 'GET',
        headers: {
            'Accept': 'image/jpeg',
            'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxx'
        }
    }).then(res => res.blob());
}

When calling the API I update my state with the Blob Object ...

    ApiService.find("955a3576").then(res => {
      this.setState({myImage: res});
    })

... and am able now to display the image with URL.createObjectURL

<img src={this.state.myImage ? URL.createObjectURL(this.state.myImage) : null}></img>

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