简体   繁体   English

如何从后端下载图像并将其显示在img标签中?

[英]How would I download an image from my backend and display it in an img tag?

I want to download an image from my REST API with axios and display it in an img tag. 我想使用axios从我的REST API下载图像并将其显示在img标签中。 Can I do this without locally saving the file? 我可以在不本地保存文件的情况下执行此操作吗?

I had used <img src="localhost/api/imgs/1"/> so far, but I'm securing the endpoint with token management now. 到目前为止,我已经使用<img src="localhost/api/imgs/1"/> ,但是现在我要通过令牌管理来保护端点。

Any ideas how this is normally done? 任何想法通常如何完成?

It looks like you are also using React. 看来您也在使用React。 Are you able to save the image to the state and then pass it along as the source? 您是否可以将图像保存到状态,然后将其作为源传递?

import React, { Component } from "react";
import API from 'wherever you are calling axis from';

class YourClass extends Component {
state = {
img = ""
}

getImage = () => {
API.getImage()
.then(res =>
this.setState({ img: res.data })
)
.catch(error => console.log(error)
}

render() {
<div>
<img src={this.state.img}>
</div>
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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