user2994290
user2994290

Reputation: 329

Save file inside Documents/Downloads react-native

Is it possible to save files with react-native inside Documents or Downloads? I am trying to save a pdf file with react-native-fs:

let file = await RNHTMLtoPDF.convert(options)
const destinationPath = RNFS.DocumentDirectoryPath + "/" + fileName + ".pdf"
RNFS.copyFile(file.filePath, destinationPath)

but it is saved in the root directory (/data/user/0/com.prodhealth.mobile.Dev/files/TestTest_2022-02-22_2022-02-22.pdf) which is not accessible for normal users.

Is there a way to save it directly in Documents/Downloads of internal storage of the phone? I need that user can easily access this file.

Upvotes: 5

Views: 12101

Answers (2)

hari r
hari r

Reputation: 1

Yes, You can. It's working for me.

        let file = await RNHTMLtoPDF.convert(options);
        const destinationPath = RNFS.DownloadDirectoryPath;
        const FileName = 'filename.pdf';

        const destinationFile = destinationPath + "/" + FileName;
        
        RNFS.copyFile(file.filePath, destinationFile)
            .then(result => {
                
                // Delete a file on the project path using RNFS.unlink
                return RNFS.unlink(file.filePath)
                    .then(() => {
                        console.log('FILE DELETED');
                    })
                    // `unlink` will throw an error, if the item to unlink does not exist
                    .catch((err) => {
                        console.log(err.message);
                    });
            })
            .catch(err => {
                console.log('err', err);
            }); 

Upvotes: 0

hong developer
hong developer

Reputation: 13906

you can use react-native-fetch-blob

  • cp(src:string, dest:string):Promise

dirs This constant is a hash map containing commonly used folders:

  • DocumentDir
  • MainBundleDir (Can be used to access files embedded on iOS apps only)
  • DownloadDir (Android Only)

Example

RNFetchBlob.fs.cp(SRC_PATH, DEST_PATH)
.then(() => { ... })
.catch(() => { ... })

Upvotes: 2

Related Questions