【问题标题】:How to display image returned from fetch() method - react-native如何显示从 fetch() 方法返回的图像 - react-native
【发布时间】:2020-05-20 04:13:54
【问题描述】:

我有以下代码从 API 中检索图像

await fetch('https://example.com/api/user/fileaccess', {
    method: 'POST',
    headers: {
      Accept: '*',
      'Content-Type': 'application/json',
      'token':'xxxxxxxxxxxxxxxxxxxxxxxx'
    },
    body:  JSON.stringify({"applicantid": xxxx, "user_secret": "xxxxxxxxxxx","fileid":xxxxx}),
  }).then((response) => {
    console.log(response);
  }); 

请求已完成,我已登录控制台。

{"_bodyBlob": {"_data": {"__collector": [对象], "blobId": “xxxxx-xxxx-xxx-xxxx-xxxxx”,“偏移”:0,“大小”:953328}}, “_bodyInit”:{“_data”:{“__collector”:[对象],“blobId”: “xxxxx-xxxx-xxxx-xxxx-xxxxx”,“偏移”:0,“大小”:953328}}, “标题”:{“地图”:{“缓存控制”:“max-age = 2592000”,“连接”: “Keep-Alive”、“content-type”:“image/jpeg”、“date”:“2020 年 2 月 4 日星期二 格林威治标准时间 10:34:14", "过期": "2020 年 3 月 5 日星期四 10:34:14 格林威治标准时间", “保持活动”:“超时=5,最大值=100”,“编译指示”:“公共”,“服务器”: “Apache”,“传输编码”:“分块”}},“ok”:true,“status”:200, “statusText”:未定义,“类型”:“默认”,“url”: "https://example.com/api/user/fileaccess"}

我的问题是,如何在我的应用中将此数据显示为图像?是否可以将此数据转换为 base64?

【问题讨论】:

  • 那个网址有你的图片吗?
  • 是的,我可以在邮递员中看到它

标签: reactjs react-native fetch


【解决方案1】:

如果这是图片网址,您可以按照以下方式进行操作 将图像存储在您的状态

this.setState({image:res.url})

然后<Image source={{uri:this.state.image}}/>

【讨论】:

    【解决方案2】:

    您需要先将其提取到 json 或 text 或其他一些数据中,然后才能对响应进行任何操作。

    根据Mozilla docs,设置一个基本的获取请求非常简单。看看下面的代码:

    fetch('http://example.com/movies.json')
      .then((response) => {
        return response.json();
      })
      .then((myJson) => {
        console.log(myJson);
      });
    

    所以,修改你的代码如下:

    fetch('https://example.com/api/user/fileaccess', {
        method: 'POST',
        headers: {
          Accept: '*',
          'Content-Type': 'application/json',
          'token':'xxxxxxxxxxxxxxxxxxxxxxxx'
        },
        body:  JSON.stringify({"applicantid": xxxx, "user_secret": "xxxxxxxxxxx","fileid":xxxxx}),
      })
    .then(response => response.json())
    .then((result) => {
         console.log("Your intended result is: " , result)
    }); 
    

    添加response.json() 只是假设服务器正在返回 JSON 数据。 如果没有,您也可以根据您的服务器实现尝试以下方法。

    数组缓冲区() 斑点() json() 文本() 表单数据()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      • 2019-07-03
      • 2018-03-01
      • 2018-11-12
      • 2016-11-08
      相关资源
      最近更新 更多