【问题标题】:How would I download an image from my backend and display it in an img tag?如何从后端下载图像并将其显示在 img 标签中?
【发布时间】:2019-09-07 06:30:46
【问题描述】:

我想使用axios 从我的REST API 下载图像并将其显示在img 标记中。我可以在不本地保存文件的情况下执行此操作吗?

到目前为止,我一直使用<img src="localhost/api/imgs/1"/>,但我现在正在使用令牌管理来保护端点。

你知道这通常是怎么做的吗?

【问题讨论】:

    标签: javascript reactjs image


    【解决方案1】:

    看起来你也在使用 React。您是否可以将图像保存到状态,然后将其作为源传递?

    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>
    }
    }
    

    【讨论】:

    • 我确实尝试过这样,但不幸的是它不会以这种方式呈现图像数据。我是否必须先转换 res.data 才能将其用作 src 属性?
    • here 一样转换它,也许更新你的答案,包括这个。
    猜你喜欢
    • 2016-02-07
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2014-09-29
    相关资源
    最近更新 更多