rn-fetch-blob错误:RNFetchBlob.fetchBlobForm无法创建请求正文

时间:2020-02-12 10:59:07

标签: reactjs react-native react-redux react-native-ios rn-fetch-blob

async postFileUpload(payload) {
    const rnfetchfile = RNFetchBlob.wrap(payload.uri);
    try {
    console.log(
        'POST',
        'https://******.***.**/******/***/upload_*******_file',
        {
          ...this.config,
          'Content-Type': 'multipart/form-data',
        },
        [
          // element with property `filename` will be transformed into `file` in form data
          {
            name: 'files',
            filename: payload.name,
            data: rnfetchfile.replace('file://file:///', 'file://'),
          },
        ],
      );
      const res = await RNFetchBlob.fetch(
        'POST',
        'https://******.***.**/******/***/upload_*******_file',
        {
          ...this.config,
          'Content-Type': 'multipart/form-data',
        },
        [
          // element with property `filename` will be transformed into `file` in form data
          {
            name: 'files',
            filename: payload.name,
            data: rnfetchfile.replace('file://file:///', 'file://'),
          },
        ],
      );
    const response = JSON.parse(res.data);
      console.log('api upload adpostimage', response);
      return response;
    } catch (err) {
      console.log('postFileUpload', err.response, err);
      Toast.show(err.response.data.message, Toast.SHORT);
      throw err.response.data;
    }

res抛出错误 在控制台消息中

POST https://******.***.**/******/***/upload_*******_file {Content-Type: "multipart/form-data", Authorization: "Bearer ******.***.*****"} 
[{…}]
0:
name: "files"
filename: "*****.pdf"
data: "RNFetchBlob-file://Users/********/tmp/*****/B****.pdf"}
postFileUpload undefined Error: RNFetchBlob.fetchBlobForm failed to create request body
at index.js:313
at MessageQueue.__invokeCallback (MessageQueue.js:483)
at MessageQueue.js:135
at MessageQueue.__guard (MessageQueue.js:384)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:134)
at debuggerWorker.js:69

我正在尝试使用rn-fetch-blob上传文件,并且发生了一些疯狂的事情 rnfetchfile.replace('file:// file:///','file://'),因为file:// file ///输出似乎不正确 我认为这主要是ios问题,请帮帮我

2 个答案:

答案 0 :(得分:8)

here所说的只是使用decodeURIComponent(uri)

这是我的代码:

const realPath = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;

const data = [
  {
     name: 'file',
     filename,
     type,
     data: RNFetchBlob.wrap(decodeURIComponent(realPath)),
  },
  {name: 'bla', data: 'bla'}
]

答案 1 :(得分:0)

尝试将file:// file://替换为''空字符串。

rnfetchfile.replace('file://file:///', '') 

– @Abhishek Ghosh评论说这是一个有用的技巧,它将起作用,但该文件在uri中将不可用。您上传的文件将不会打开

我尝试做

data: decodeURIComponent(rnfetchfile.replace('file://file:///', 'file:///')

,并且希望能对您有所帮助