Downloading & viewing bytearray file in React native

Photo by Neil Soni on Unsplash

Hey friends, You must have came across a scenerio where you have to download a file to your react native app. Compared to the web it is a little bit tricky as you have to rely on different packages for it. But once you know it, it’s easy as anything.

Here we are considering that we get the filebyte array in the response, instead of the direct image url.

For this, we need to take the help of two packages. And those are

  • react-native-fs
  • react-native-file-viewer

Lets add these packages

npm install react-native-fs --save
npm install react-native-file-viewer --save

To follow the other installation steps for react-native-fs & react-native-file-viewer , you can visit their github page here and here respectively.

Steps

  1. Download the filebyte array response from the fetch api
  2. Save the api response using react-native-fs
  3. Open the file using react-native-file-viewer

Code

We will be saving the file inside the DocumentDirectoryPath, there are other many different options you can choose from.

Lets look at the code.

import RNFS from "react-native-fs";
import FileViewer from "react-native-file-viewer";

const downloadAndOpen = async() => {
  try {
  let response = await fetch({
    url,
    method: "POST",
  });
  const location = `${RNFS.DocumentDirectoryPath}/myFile.txt`;
  await RNFS.writeFile(location, response.FileData, "base64");
  await FileViewer.open(location);
  } catch(err) {
    console.log(err);
  }
}

Hope this little code helped you in figuring it out that how to save and view the images.

Thanks for reading.. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *