我从后端获取图像并尝试使用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");
也可能是因为反应需要json格式而不显示的原因? 提前谢谢!
答案 0 :(得分:1)
当你可以将它设置为src时,无需使用fetch并将其解析为json或base64:
<img alt="" src={"/hunter/picture?page=" + this.props.match.params.id} />