首页 > 解决方案 > 如何从快速后端服务器获取和显示图像到 React Native 前端?

问题描述

搜索同一主题时,我发现了另一个问题: 如何从快速后端服务器获取和显示图像到 React js 前端? 并且在评论中有这样的:“将你的 blob 转换为 File var file = new File( res.data, { type: "image/jpeg" } ); var imageUrl = URL.createObjectURL(file); 然后使用这个 imageUrl ”。所以我做了类似于他的代码并得到了错误。

fetchImages = () => {
 const imageName = 'Vinicius_0-1577392361334.jpg';
 api.get(`/image/${imageName}`)
  .then(res => {
    var file = new File(res.data, { type: 'image/jpg' });
    var imageURL = URL.createObjectURL(file);
    return (
      <Image source={imageURL} />
    )
  }).catch((err) => {
    console.log(err)        
  });}
routes.get('/image/:file', (req,res) =>{
  let file = req.params.file;
  let fileLocation = path.join(__dirname, '..', '..', 'backend/uploads/', file);

  res.sendFile(`${fileLocation}`);
});
         .....
<View style={styles.viewBotao}>
     {this.fetchImages()}
         .....

控制台输出

标签: javascriptnode.jsreactjsreact-nativeexpress

解决方案


尝试将您分配imageURL给状态变量

constructor(props) {
    super(props);
    this.state = {
        imageURL: ''
    }
}

fetchImages = () => {
    ...
        var imageURL = URL.createObjectURL(file);
        this.setState({ imageURL });
    ...
}


<View style={styles.viewBotao}>
     <Image source={this.state.imageURL} />
</View>

推荐阅读