Skip to content

Unable to download file in Android 11 (ENOENT: no such file or directory, open '/storage/emulated/0/fileName.pdf')Β #950

Open
@pankajnegi1893

Description

@pankajnegi1893

I am trying to download the File in Android 11 but unable to download the file. Every time it's giving ENOENT: no such file or directory, open '/storage/emulated/0/fileName.pdf' error.

FileHelper.js

const { PermissionsAndroid, Platform } = require("react-native");
         import RNFS from "react-native-fs";
         const requestStoragePermission = async () => {
         try {
               const granted = await PermissionsAndroid.request(
                 PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                 {
                   title: "Storage Permission",
                  message: "requires Storage Permission",
                  buttonNegative: "Cancel",
                  buttonPositive: "OK",
               },
            );
             if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                return true;
            } else {
              return false;
            }
            } catch (err) {
               console.warn(err);
                 return false;
            }
         };

    export const FILE_TYPE = {
        UPLOADING_START: 'uploadingStart',
        UPLOADING: 'uploading',
        DOWNLOADING_START: 'downloading_start',
        DOWNLOADING: 'downloading',
        FINISHED: 'finished',
     };

    export const downloadPDFFile = async (
         callback,
         serverFilePath = "https://www.mathworksheets4kids.com/add-sub/3by2-1.pdf",
         serverFileName = "3by2-1.pdf",
       ) => {
         try {
              if (Platform.OS == 'android') {
             const isPermissionGranted = await requestStoragePermission();
             if (!isPermissionGranted) {
                alert('You have cancelled the permission');
                 return;
             }
         }
          let path;
          let serveFileNameReplace = serverFileName.replace(/ /g, "%20");
          let serverURL = serverFilePath.replace(/ /g, "%20");
          if (Platform.OS == 'ios') {
              path = `${RNFS.DocumentDirectoryPath}/${serveFileNameReplace}`;
          } else {
             path = `${RNFS.ExternalStorageDirectoryPath}/${serveFileNameReplace}`;
         }
           console.log("===>",path);
         RNFS.downloadFile({
          fromUrl: serverURL,
          toFile: path,
          background: false,
          cacheable: false,
          connectionTimeout: 60 * 1000,
           readTimeout: 120 * 1000,
           begin: (res) => {
 
            console.log('begin :- ', res);
            callback({
               status: FILE_TYPE.DOWNLOADING_START,
               percentage: 0,
             });
         },
       progress: (res) => {
            console.log('res :- ', res);
           let percentage
            if(res.contentLength == -1){
             percentage = 0;
            }else {
              percentage = (res.bytesWritten * 100) / res.contentLength;
              percentage = Math.round(percentage);
           }
           if (percentage >= 100) {
             callback({
                status: FILE_TYPE.FINISHED,
               percentage: percentage,
           });
         } else {
           callback({
             status: FILE_TYPE.DOWNLOADING,
             percentage: percentage,
             path: path,
           });
         }
       },
       
     }).promise.then((res) => {
       console.log('res :- ', res);
       callback({
         status: FILE_TYPE.FINISHED,
         percentage: 100,
         path: path,
       });
     }).catch((err) => {
       console.log(err);
       alert(err);
     });
   } catch (err) {
     if (err.description === 'cancelled') {
       // cancelled by user
     }
     console.log(err);
     }
   };```

App.js 
    import React from 'react';
    import {
      SafeAreaView,
     View,
     Text,
     StatusBar,
     TouchableOpacity,
     } from 'react-native';
    import {downloadPDFFile} from './src/FileHelper';

  const App = () => {
      return (
             <>
               <StatusBar barStyle="dark-content" />
              <SafeAreaView>
                    <View style={{flex:1, marginTop: '50%', marginLeft: '10%'}}>
                         <TouchableOpacity 
                                  style={{
                                         justifyContent:'center',
                                         alignItems:'center',
                                         width: '80%',
                                         height: 40,
                                         backgroundColor: 'green'
                                     }}
                                onPress={() => {
                                      downloadPDFFile((res) => {
                                                console.log(res);
                                      });
                                 }}>
                              <Text style={{color: '#000000'}}>Download File</Text>
                        </TouchableOpacity>
                    </View>
             </SafeAreaView>
          </>);
      };
     export default App;

AndroidManifest:-

  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
       package="com.awesomeprojectandroid11">

     <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
         tools:ignore="ScopedStorage" />
       <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
       <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
       <application
         android:name=".MainApplication"
         android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:allowBackup="false"
        android:preserveLegacyExternalStorage="true"
        tools:ignore="GoogleAppIndexingWarning,UnusedAttribute"
        android:theme="@style/AppTheme">
       <activity
          android:name=".MainActivity"
          android:label="@string/app_name"
          android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
          android:launchMode="singleTask"
           android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
  </activity>
  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>

react-native-fs I am using to download the File. But it's not working. 

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions