如何在React-Native中使用RNfetchblob上传多部分/表单数据?

时间:2018-07-17 06:40:10

标签: javascript react-native react-native-android fetch-api

这是我尝试使FormData看起来不错的代码。

但是我不确定如何使用数据字段处理uri,我应该编码为base64吗?

  RNFetchBlob
    .fetch("POST",`${config.apiHost}/${path}`,{ 
        "Authorization" : token,
        "X-AUTH-SECURE" : secure,
        'Content-Type': 'multipart/form-data'
    },
        [
          { name : String(payload.fileName),
            filename:payload.fileName,
            data :RNFetchBlob.wrap(payload.uri) }  
        ]
     )
     .uploadProgress((written, total) => {
         console.log("Upload", Math.floor(written/total * 100))
      })
     .then(response => {
         if(response.status===401){
               return;
         }
         console.log('The file upload ', response)
     }).catch(error=>{
         console.log(error);
     }); 

然后我从console.log得到了响应

"{"state":"error","code":0,"message":"internal server error","debug":"Error: Unexpected field\n    at makeError (C:\\ ... blah

如何解决这个问题?

plus)参考库: https://github.com/joltup/rn-fetch-blob

1 个答案:

答案 0 :(得分:0)

以以下格式发送文件

const filePath = filepathOriginal.replace('file://', '');
    const filename = filepathOriginal.replace(/^.*[\\\/]/, '');

    [
      {
        name: 'multipartFile', filename, type: 'image/jpg', data: RNFetchBlob.wrap(filePath),
      },
    ]