react-native-android-files

A react-native module which is used to pick, open, upload and download files.

Usage no npm install needed!

<script type="module">
  import reactNativeAndroidFiles from 'https://cdn.skypack.dev/react-native-android-files';
</script>

README

react-native-android-files

A simple react-native module which is used to pick, open, upload and download files.

Getting Started

Installation

Using npm

$ npm install react-native-android-files --save

Using yarn

$ yarn add react-native-android-files

Linking

There are two options for linking:

1. Automatic

react-native link react-native-android-files

2. Manual

If the automatic linking fails for some reason, you can do the linking manually as follows:

  • add the following to yourAppName/android/settings.gradle file:
 include ':react-native-android-files'
 project(':react-native-android-files').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-android-files/android')
  • add the following inside the dependencies closure of yourAppName/android/app/build.gradle file:
 implementation project(':react-native-android-files')
  • add the following to your MainApplication.java file:
 import com.adfiles.files.FilesPackage;

and also,

 @Override
 protected List<ReactPackage> getPackages() {
   return Arrays.<ReactPackage>asList(
     new MainReactPackage(),
     ....
     new FilesPackage()                       <== Add this
   );
 }

Usage

To perform activities on with the module, first import the it to your app like so:

import { Files } from 'react-native-android-files';

After this, you can call any of the functions stated below as appropriate.

Functions

The files module contains the following functions.

        open(String path)
        getPath()
        pick()
        download(String src, String dest)
        upload(String dest)

Permissions

No permission is required open a file picker dialog with getPath() function and to obtain the path of the selected file as a response. However, to download a file and to save it on the device with download() function, only the first configuration, i.e., adding the storage permission, is required. In addition, to open a file for a given path from the device with open() function or to pick a file from a dialog and to open it via pick() function, the following configurations should be made. For API level 23 and below devices, only the first configuration is required. For API level 24 and above, all the three configurations are mandatory. The third configuration can be changed according to official android documentation regarding FileProvider class.

  1. Add the following permission outside the application tage of the AndroidManifest.xml file.
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
  1. Add the following provider tag within the application tag in the AndroidManifest.xml file.

      <provider
               android:name="android.support.v4.content.FileProvider"
               android:authorities="${applicationId}"
               android:exported="false"
               android:grantUriPermissions="true">
               <meta-data
                   android:name="android.support.FILE_PROVIDER_PATHS"
                   android:resource="@xml/provider_paths">
               </meta-data>
       </provider>
  1. Create a folder named xml inside yourAppName\android\app\src\main\res (if there isn't any) and create a file named provider_paths.xml inside the folder and add the following content in the file. As stated above, the contents of this file can be changed to meet your desired accessible file locations.
    <?xml version='1.0' encoding='utf-8'?>
        <paths xmlns:android="http://schemas.android.com/apk/res/android">
            <root-path name="root" path=""/>
            <files-path name="files" path="/" />
            <external-files-path name="external_files" path="" />
            <external-path name="external" path="." />
            <cache-path name="cache" path="/" />
        </paths>

Description

The above functions are used to perform the following activities.

🔷 open(String path):

is used to open a file from a location specified by the path parameter. A number of common file types will be opened by calling this function via the default app on the device. Note that the device should have an installed app to open the given file type. For instance, if you want to open a pdf file, the file will be opened successfully only if there is a pdf viewer installed on the device.

Sample code snippet
            import { Files } from 'react-native-android-files';
            ....
            ....

            _openFile = () => {
                const path = "/storage/emulated/0/DCIM/Camera/myPic.jpg";
                Files.open(path).catch((err) => {
                    console.log("error");
                });
            } 

Call to _openFile() will open the specified file for successful requests or a promise rejection will be sent if something goes wrong.

🔷 getPath():

is used to get a path of a file where a file picker dialog will be opened and the user picks any file from the device. For successful requests, the path of the selected file will be sent as a response or a promise rejection otherwise.

Sample code snippet
            import { Files } from 'react-native-android-files';
            ....
            ....

            _getFilePath = () => {
                Files.getPath().then((path) => {
                    console.log(path);
                }).catch((err) => {
                    console.log(err);
                });
            } 
Sample result

Call to _getFilePath() function opens a file picker dialog, waits for a user to select a file and logs the path of the selected file. A sample response may look like the following:

                "file:///storage/emulated/0/Download/myfile.mp4"

🔷 pick():

is used to open file picker dialog so that the user can pick and open a file from the device. Note that, for API level 24 and above, in order to successfully open the desired file, the correct configuration should be made to grant access to the desired file location as described above.

Sample code snippet
            import { Files } from 'react-native-android-files';
            ....
            ....

            _openFileFromPicker = () => {
                 Files.pick().catch((err) => {
                    console.log(err);
                 });
            } 

Call to _openFileFromPicker() function opens a file picker dialog, waits for a user to select a file and opens the file if access is rightfully granted.

🔷 download(String src, String dest):

is used to download file from src to dest. The src parameter can be either a file location on the device or a webservice. If it is the former one, the actual file location should be preceded by a protocol, i.e., file://. The dest parameter can be either a presumed complete file path or a directory where the downloaded file will be stored. You use the former one if you know the file mime type before downloading and you want to give your own custom name to the file. Where as the latter is used if you want the downloaded file to take the same name as it has in the source location.

Sample code snippet
            import { Files } from 'react-native-android-files';
            ....
            ....

            _downloadFile = () => {
                const src = "http://www.mywebservice.com/download/myVideo.mp4",
                      dest = "/storage/emulated/0/videos/";
                Files.download(src, dest).catch((err) => {
                    console.log(err);
                });
            } 

Call to _downloadFile() function downloads a file from the webservice specified by src variable and saves it in a directory specified by dest variable.

🔷 upload(String dest):

is used to upload a file picked from the device on to a webservice specified by dest parameter. Note that, for API level 24 and above, in order to successfully upload the desired file, the correct configuration should be made to grant access to the desired file location as described above.

Sample code snippet
            _uploadFile = () => {
                const dest = "http://www.mywebservice.com/upload";
                Files.upload(dest).catch((err) => {
                    console.log(err);
                });
            } 
Sample result

Call to _uploadFile() function opens a file picker dialog, waits for a user to select a file and uploads the selected file to a webservice specified by dest parameter if access is rightfully granted.

Issues or suggestions?

If you have any issues or if you want to suggest something , you can write it here.

Additional info

This is a component of a more comprehensive react-native-system-applications module developed by the same author.