ReactNative Android is not saving the file to the external storage

748 Views Asked by At

I am building an Android application using ReactNative. My application needs to write a file to the external storage. I am using this library for that, https://www.npmjs.com/package/react-native-fs. This is what I have done so far.

I have the following permissions in the AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Then I request permission as follow

const requestPermissions = async () => {
        console.log("Requesting the permissions")
        let granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
            {
                'title': 'Write File Permission',
                'message': 'The app needs the permission to save the file to the device storage.'
            }
        )

        if (granted ==  PermissionsAndroid.RESULTS.GRANTED) {
            Alert.alert("Permission", "Request has been granted")
        } else {
            Alert.alert("Permission", "Request was not granted")
        }
    }

Then I import the library as follow.

var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + "/test.txt"

Then I save the file as follow

const saveAsFile = () => {
        RNFS.writeFile(path, message, 'utf8')
            .then(success => {
                Alert.alert("Save", "File has been saved")
            })
            .catch(error => {
                console.log(error)
                Alert.alert("Save", "Unable to save the file")
            })
    }

It was not throwing error. The success callback was called. But I can't see the file on the Documents folder of the device. What's wrong with my code and why the file is not created on the device?

0

There are 0 best solutions below