【问题标题】:Uploading a Photo in React Native to a Node Server将 React Native 中的照片上传到节点服务器
【发布时间】:2017-11-03 19:57:52
【问题描述】:

尝试使用名为“react-native-fetch-blob”的 React 库上传本地资产(简单的 jpeg 文件)。我的服务器正在记录请求,但是无论我尝试什么,req.body 要么是空的,要么是未定义的。

我已尝试将文件作为“base64”编码字符串上传,但还是没有成功。

我也知道我的 uri 是有效的。

前端代码:

 RNFetchBlob.fetch('POST', 'http://localhost:3000/api/analyze', {
      'Content-Type': 'multipart/form-data'
    }, RNFetchBlob.wrap(this.state.imgSource.uri))
    .then( res => {
      console.log('success:', res);
    })
    .catch( err => {
      console.log('error:', err);
    })

我在后端使用 express 以及 express-formidable 包来解析 multipart/form-data。

任何帮助将不胜感激!我也花了很多时间在问题跟踪器中为我正在使用的每个包,似乎找不到哪里出了问题。

【问题讨论】:

    标签: javascript node.js react-native multipartform-data


    【解决方案1】:

    尝试使用原生的fetch API 和FormData 对象。类似的东西:

      const postImage = (imagePath) => {
        const photo = {
          uri: imagePath,
          name: 'image.jpg',
          type: 'image/jpeg',
        };
        const data = new FormData();
        data.append('file', photo);
        const config = {
          method: 'POST',
          body: data,
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        };
        return fetch("https://your.endpoint/img", config);
      }
    
      postImage(pathToYourFile)
        .then(resp => resp.json())
        .then(json => console.log(json))
        .catch(err => console.log(err))
    

    这样 React Native 就知道如何将给定的路径转换为多部分请求。

    【讨论】:

    • 嘿,谢谢兄弟!这是一个非常干净的回应,我真的很感激。我最终使用了库的本地实现 fetch。基本上我必须做你在这里所做的,结构有点不同。再次感谢!学到了很多关于 MIME 类型的知识。
    • @N.Pisciotti 很高兴我能帮上忙 :) 如果对您有帮助,请接受正确的答案。谢谢!
    • 如果文件扩展名是动态的怎么办?就像使用 react-native-document 选择器时一样,您可以选择多种文件类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 2019-11-28
    • 2021-10-09
    • 2012-06-23
    相关资源
    最近更新 更多