0

In order to download an asset an Authorization header needs to be set when using react-native-fs with React Native.

Following the documentation the header is set as such:

  const options = {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
    fromUrl: url,
    toFile: path,
  };

  // const permission = await insurePermissions();

  const task = RNFS.downloadFile(options);

It works perfect in iOS however Android, using an emulator running either Android 6, 8, 9, or 10, the header isn't being sent so the server is instead returning a different asset with error because the user isn't being authenticated.

How is the Authentication header set in Android with react-native-fs?

Adam S
  • 468
  • 8
  • 22

1 Answers1

0

This problem is consistent with other React Native file system libraries. I instead used Axios to download the file and saved with with RNFS.

const fetchFile = async (accessToken, id) => {
  const dir = await getDirectory();
  await flushFileProofs();
  const baseUrl = 'https://example.com';
  const url = `${baseUrl}/images/${id}/download`;
  const fileName = `${id}-file.png`;
  const path = `${dir}/${fileName}`;

  const data = await axios.request({
    method: 'GET',
    url,
    headers: {
      Accept: '*/*',
      Authorization: `Bearer ${accessToken}`,
    },
    responseType: 'arraybuffer',
  })
    .then(response => Buffer.from(response.data, 'binary').toString('base64'));

  await RNFS.writeFile(path, data, 'base64');
  FileViewer.open(path);
};
Adam S
  • 468
  • 8
  • 22