reactjs - 在 REACT 中显示图像

标签 reactjs jpeg fetch

我从后端获取图像并尝试使用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/

相关文章:

git svn 获取特定目录

python - 使用 Python 将 PDF 转换为一系列图像

transparency - 网站上带有 alpha channel 的 JPEG 图像

javascript - 我可以在尝试预加载 XHR 数据时添加自定义标题吗?

javascript - 构建多 View 、多用户类型的 React 应用程序

java - 使用 Java 在 JPEG 中存储 DPI 和纸张尺寸信息

iPhone 核心数据 - 获取的托管对象未在设备上发布(在模拟器上很好)

reactjs - 毫无痛苦地脱离世博会

javascript - 使用 fetch w/react js 访问返回的 promise 中的对象

javascript - React 应用程序,绝对定位的子项不是相对于其相对定位的父项定位的(在 Chrome 中)