postreact-nativex-sendfile

Downloading a binary file with POST method in React Native


I am using React-native on the front end with a PHP backend on my server. I need to be able send a passcode to the server that I want to download a file from. I am connecting to a PHP script which is using the X-SendFile library to send the file back if the passcode was correct.

Currently I am using RNFS.downloadFile() to download and save files, but that only seems to work with GET and not with POST. I would prefer to be able to save the files to the DocumentDirectoryPath.

My current code looks like this:

await RNFS.downloadFile({
    fromUrl: 'http://example.com/myfile.zip',
    toFile: RNFS.DocumentDirectoryPath + "/userdata/myfile.zip",
}).promise

I would like to be able to do something like this:

await RNFS.downloadFile({
    method: post,
    body: {passcode: "abc123", filename: "myfile.zip"},
    fromUrl: 'http://example.com/getfile.php',
    toFile: RNFS.DocumentDirectoryPath + "/userdata/myfile.zip",
}).promise

How can I change my code so that it passes the passcode as a POST parameter?


Solution

  • As it can be seen in the following file, lines 58 through 70, react-native-fs does not support what you are trying to achieve.

    FS.common.js @ react-native-fs github page

    However, there are other libraries that can help you. react-native-fetch-blob supports what you are trying to achieve in the following format;

    RNFetchBlob
    .config({
      path : RNFetchBlob.fs.DocumentDir + '/userdata/myfile.zip'
    })
    .fetch(
      'POST',
      'http://example.com/myfile.zip',
      {
        //headers...
      },
      JSON.stringify({
        //request body...
        passcode: "abc123",
        filename: "myfile.zip"
      }),
    )
    .then((res) => {
      console.log('The file saved to ', res.path())
    })
    

    While it should work this way, I'd advise you not to resort to this and use Authentication schemas for auth such as HTTP Basic Auth and query strings / headers for other data while trying to download files and use GET requests.