【问题标题】:How to Fetch and Display an Image from an express backend server to a React Native frontend?如何从快速后端服务器获取和显示图像到 React Native 前端?
【发布时间】:2020-04-17 03:01:03
【问题描述】:

搜索同一主题,我发现了另一个问题: How to Fetch and Display an Image from an express backend server to a React js frontend? 在 cmets 中有这样的:“将你的 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()}
         .....

Console OutPut

【问题讨论】:

    标签: javascript node.js reactjs react-native express


    【解决方案1】:

    尝试将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>
    

    【讨论】:

    • 谢谢!但这会引发错误TypeError: parts.map is not a function at Function.createFromPart。进行更多研究后,我发现问题可能是我无法转换为文件的 blob 响应。
    • 是的,我只是告诉你处理imageURL的方法。您可以尝试使用github.com/joltup/rn-fetch-blob 来下载您的文件。
    • 就我而言,我认为下载文件没有意义,因为客户端会有一个服务列表,每个服务都会有一个相关的图像。如果客户端打开每个服务,将下载服务器中的所有图像。
    猜你喜欢
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2021-07-26
    • 2021-12-03
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多