我从后端获取图像并尝试使用react将其显示在前端。 我想当我获取文件时我没有将图像正确设置到文件中。 因为,我收到了服务的响应:
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAg ...
这是我的代码:
constructor(props) {
super(props);
this.state = {
file: []
}
}
fetchPicture(){
const {match} = this.props
const id = match.params.id
const { file } = this.state;
fetch("/hunter/picture?page=" + id)
.then(res => res.json())
.then(file => this.setState({ file }));
}
render() {
return(
<Form>
<img alt="" src={`data:image/jpg;base64,${this.state.file}`}/>
</Form>
)
}
}
最重要的是,我的控制台上有这个:
Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
当我从后端发送它时,我将内容类型设置为jpg。
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "image/jpg");
也可能是因为react需要json格式而不显示的原因吗? 预先感谢您!
最佳答案
当您将其设置为 src 时,无需使用 fetch 并将其解析为 json 或 base64:
<img alt="" src={"/hunter/picture?page=" + this.props.match.params.id} />
关于reactjs - 在 REACT 中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47743360/