Forad
Forad

Reputation: 173

Saving a files in React-Native using react-native-fs library

After saving a file using react-native-fs where does that file go?

It's not explained in the documentation or I couldn't find and it's hard to figure.

Upvotes: 14

Views: 24611

Answers (2)

Kishan
Kishan

Reputation: 154

i got another way using RNFS from 'react-native-fs' where im storing Pdf file to FireBase Storage.

Firstly im finding the Absolute Path of selected PDF
secondly copying that file to locally,then getting exact path of copied Tempfile and uploading that,
Once uploading done to Cloud i deleted Locally saved temp Pdf file  

Hence Problem solved

import RNFS from 'react-native-fs';


 try {
      let Filename = fileName.split('.').slice(0, -1).join('.');
      const extension = fileName.split('.').slice(1).join('.');
      const NameWithoutExtension = Filename.split('.').slice(0, -1).join('.');
      Filename = Filename + Date.now() + '.' + extension;
      // console.log('extension:', Filename);

      setLoader(true);
      RNFS.copyFile(file, RNFS.DownloadDirectoryPath + '/tempFile.' + extension)
        .then(copyResponce => {
          console.log('copyResponce:', copyResponce);
          RNFS.exists(RNFS.DownloadDirectoryPath + '/tempFile.' + extension)
            .then(isexist => {
              console.log('isexist:', isexist);

              const StorageRef = storage().ref(`ResumeData/${Filename}`);
              StorageRef.putFile(
                RNFS.DownloadDirectoryPath + '/tempFile.' + extension,
              )
                .then(async res => {
                  const url = await StorageRef.getDownloadURL();
                  console.log('fileuploaded:', url);
                  console.log('res:', res);
                  //adding data to firebase cloud
                  await firestore()
                    .collection(DB_Name.all_resource)
                    .add({
                      Name: Name,
                      Experience: Experience,
                      Technology: service,
                      Contact: Phone,
                      Resume: url,
                      senderId: uid,
                    })
                    .then(() => {
                      console.log('Resource Post Success!');
                      navigation.goBack();
                      setLoader(false);
                      setExperience(null);
                      setName(null);
                    });
                  // Removing Temp stored file
                  RNFS.unlink(
                    RNFS.DownloadDirectoryPath + '/tempFile.' + extension,
                  )
                    .then(del => {
                      setLoader(false);
                      console.log('delete Tempfile Success!', del);
                    })
                    .catch(error => {
                      setLoader(false);
                      console.log('Error in Deleting Tempfile:', error);
                    });
                })
                .catch(error => {
                  setLoader(false);
                  console.log('errorin uploading', error);
                });
            })
            .catch(err => {
              setLoader(false);
              console.log('notExist:', err);
            });
        })
        .catch(error => console.log('error in Copy Responce:', error));
    } catch (err) {
      console.log('Error In storing Pdf:', err);
    }

Upvotes: 0

Andrew
Andrew

Reputation: 28539

When you create a file you have to specify a directory where to store the file. In the example below the path variable shows where the file will be written to.

var RNFS = require('react-native-fs');

// create a path you want to write to
// :warning: on iOS, you cannot write into `RNFS.MainBundlePath`,
// but `RNFS.DocumentDirectoryPath` exists on both platforms and is writable
var path = RNFS.DocumentDirectoryPath + '/test.txt';

// write the file
RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
  .then((success) => {
    console.log('FILE WRITTEN!');
  })
  .catch((err) => {
    console.log(err.message);
  });

There are several places you can store your files

The following directories are available:

  • MainBundlePath (String) The absolute path to the main bundle directory (not available on Android)
  • CachesDirectoryPath (String) The absolute path to the caches directory
  • ExternalCachesDirectoryPath (String) The absolute path to the external caches directory (android only)
  • DocumentDirectoryPath (String) The absolute path to the document directory
  • TemporaryDirectoryPath (String) The absolute path to the temporary directory (falls back to Caching-Directory on Android)
  • LibraryDirectoryPath (String) The absolute path to the NSLibraryDirectory (iOS only)
  • ExternalDirectoryPath (String) The absolute path to the external files, shared directory (android only)
  • ExternalStorageDirectoryPath (String) The absolute path to the external storage, shared directory (android only)

So all you have to do is choose the directory. Note these directories are on the device.

Seeing the files on the device

iOS Simulator

If you want to find the file on your simulator on iOS all you need to do is console.log the path, which should look something like this

/Users/work/Library/Developer/CoreSimulator/Devices/2F8BEC88-BF42-4D6B-81D4-A77E6ED8CB00/data/Containers/Data/Application/BC16D2A6-55A2-475C-8173-B650A4E40CF1/Documents/

Open Finder, select Go to folder

enter image description here

And then paste in the path and that will open the folder where the file is.

enter image description here

Android Emulator

If you console.log the path for the file you should get something like this

/data/user/0/com.awesomeapp/files/

You have to run the app from Android Studio, then you need to access the Device View Explorer. You do that by going to View -> Tool Windows -> Device File Explorer

enter image description here

That should then open a windows that looks like this, where you can then browse to the file path that you were given above.

enter image description here

Upvotes: 26

Related Questions