[英]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" />
.我有一个带身份验证的 API,因此我不能只使用像
<img src="https://some-link.com/image.jpeg" />
这样的普通<img>
标签。
Because I have to authenticate I'm using axios to make my call to the API:因为我必须进行身份验证,所以我使用 axios 调用 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):我现在将我的图像作为 jpeg 流获取,看起来像这样(我只粘贴了整个响应数据的一小部分):
����\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)?
我正在使用 ReactJS,也许 React 有一个组件可以做到这一点(不幸的是我找不到)?
Thanks for any help.
谢谢你的帮助。
Update: Thanks you dune184 for the suggestion with the Blobs.
更新:感谢 dune184 对 Blob 的建议。 This seems promising.
这似乎很有希望。
I've created a Blob with following function:
我创建了一个具有以下功能的 Blob:
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.
我现在可以按照 dune184 的建议使用 Blob 解决我的问题。
I switched from axios to fetch, which can easly create and return a Blob Object:我从 axios 切换到 fetch,它可以很容易地创建和返回一个 Blob 对象:
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 ...调用 API 时,我使用 Blob 对象更新我的状态......
ApiService.find("955a3576").then(res => {
this.setState({myImage: res});
})
... and am able now to display the image with URL.createObjectURL
...现在可以使用
URL.createObjectURL
显示图像
<img src={this.state.myImage ? URL.createObjectURL(this.state.myImage) : null}></img>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.