joltup / rn-fetch-blob

A project committed to making file access and data transfer easier, efficient for React Native developers.
MIT License
2.81k stars 772 forks source link

[Error: Download manager download failed, the file does not downloaded to destination.] #640

Open adityakmr7 opened 3 years ago

adityakmr7 commented 3 years ago

I am trying to donwload image Here image do get to destination folder but the problem is it gives error saying

[Error: Download manager download failed, the file does not downloaded to destination.]

Code Snippets

const checkPermission = async (image: string) => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'Storage Permission Required',
            message: 'This app needs access to your storage to download Photos',
            buttonPositive: 'OK',
          },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('Storage Permission Granted.');
          handleDownload(image);
        } else {
          Alert.alert('Storage Permission Not Granted');
        }
      } catch (err) {
        console.warn(err);
      }
    }
  };
  const getExtention = (filename: string) => {
    //To get the file extension
    return /[.]/.exec(filename) ? /[^.]+$/.exec(filename) : undefined;
  };

  const handleDownload = async (image: string) => {
    let date = new Date();
    let image_url = image;
    let ext = getExtention(image_url);

    const {config, fs} = RNFetchBlob;
    let pictureDir = fs.dirs.PictureDir;
    let options = {
      fileCache: true,
      addAndroidDownloads: {
        useDownloadManager: true,
        notification: true,
        path: 
         pictureDir +
         '/wallace_' +
         Math.floor(date.getTime() + date.getSeconds() / 2) +
        '.' +
         ext,
        description: 'Image',
      },
    };
    config(options)
      .fetch('GET', image_url)
      .then((res) => res.json())
      .then((res) => {
        console.log(res.path());
        Alert.alert('Image Downloaded Successfully.');
      })
      .catch((err) => {
        console.log(err);
        // Alert.alert('Download Failed', err.message);
      });
  };
hegdeMadan commented 3 years ago

check your buildToolVersion and sdkVersion, if it's 29 then downgrade them to 28 or or upgrade versions in node_modules/rn-fetch-blob/android/build.gradle to 29 as well. I had the same permission issues to copy files.

sonisourabh commented 3 years ago

I have also faced the similar issue i.e. write file on documentDir simply crashed for me. My project configuration is:

I found a workaround in Android documentation, which is, add android:requestLegacyExternalStorage="true" in AndroidManifest.xml file:

<application android:requestLegacyExternalStorage="true" ...

Reference: https://developer.android.com/reference/android/R.attr#requestLegacyExternalStorage

Hope that this will be useful for some of you who are struggling with crash/failure of rn-fetch-blob with Android sdk 29

aftabaminzoobiapps commented 3 years ago

I have an issue. I am downloading a video file that is downloading to all other folders for example Downloads, Music, but through an error.

unsupported path /storage/emulated/0/VideoDownloader/TikTok/TIKTOKVIDEO .

` const normaldownload = dispatch => async (url, foldername , name_prefix) =>{

    let mydirs = RNFetchBlob.fs.dirs.SDCardDir
      var date = new Date()
      let checkdir = await RNFetchBlob.fs.isDir(`${mydirs}/VideoDownloader/${foldername}`);
        if(!checkdir){
          RNFetchBlob.fs.mkdir(`${mydirs}/VideoDownloader/${foldername}`).then((res) =>{
            console.log('created', res)
          }).catch((error) =>{
                console.log('Error', error)
          })
        }else{
            console.log("Dir existss")
        }

        try{  
          let options = {
            fileCache: true,
            addAndroidDownloads : {
              useDownloadManager :true, // setting it to true will use the device's native download manager and will be shown in the notification bar.
              notification : true,
              mime : 'video/mp4',
              description : 'Downloading Video',
              path:  mydirs+`/VideoDownloader/${foldername}/${name_prefix}`+Math.floor(date.getTime() + date.getSeconds() / 2) + '.mp4', // this is the path where your downloaded file will live in
            }
          }
          PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,{
              title: "Storage",
              message: "This app would like to store some files on your phone"
            }).then( async () => {  
                RNFetchBlob.config(options).fetch('GET', url).then((res) => {
                  console.log('path of the downloads ')
                  ToastAndroid.showWithGravityAndOffset(
                    `File Saved in VideoDownloader/${foldername}😃 `,
                    ToastAndroid.LONG,
                    ToastAndroid.BOTTOM,
                    25,
                    50
                  )
                }).catch((error) =>{
                  console.log(error,'ERRRROR')
                  ToastAndroid.showWithGravityAndOffset(
                    `Download Failed`,
                    ToastAndroid.LONG,
                    ToastAndroid.BOTTOM,
                    25,
                    50
                  );
              })
            })
    }
    catch(error){
      console.log("Error in catch " , error)
    }
  }

`

The above code WOrking fine on android 9 ad less but it through Error on android 10. I have already added this line. android:requestLegacyExternalStorage="true"

Still no improvement.

praveenreddy9 commented 3 years ago

I am trying to donwload image Here image do get to destination folder but the problem is it gives error saying

[Error: Download manager download failed, the file does not downloaded to destination.]

  • "react-native": "0.63.0", *"rn-fetch-blob": "^0.12.0"

Code Snippets

const checkPermission = async (image: string) => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'Storage Permission Required',
            message: 'This app needs access to your storage to download Photos',
            buttonPositive: 'OK',
          },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('Storage Permission Granted.');
          handleDownload(image);
        } else {
          Alert.alert('Storage Permission Not Granted');
        }
      } catch (err) {
        console.warn(err);
      }
    }
  };
  const getExtention = (filename: string) => {
    //To get the file extension
    return /[.]/.exec(filename) ? /[^.]+$/.exec(filename) : undefined;
  };

  const handleDownload = async (image: string) => {
    let date = new Date();
    let image_url = image;
    let ext = getExtention(image_url);

    const {config, fs} = RNFetchBlob;
    let pictureDir = fs.dirs.PictureDir;
    let options = {
      fileCache: true,
      addAndroidDownloads: {
        useDownloadManager: true,
        notification: true,
        path: 
         pictureDir +
         '/wallace_' +
         Math.floor(date.getTime() + date.getSeconds() / 2) +
        '.' +
         ext,
        description: 'Image',
      },
    };
    config(options)
      .fetch('GET', image_url)
      .then((res) => res.json())
      .then((res) => {
        console.log(res.path());
        Alert.alert('Image Downloaded Successfully.');
      })
      .catch((err) => {
        console.log(err);
        // Alert.alert('Download Failed', err.message);
      });
  };

At Path just replace .png or your image type at ext and after it's downloaded it will direclty show in Images ex: path: PictureDir + '/image' + Math.floor(date.getTime() + date.getSeconds() / 2) + ext, path: PictureDir + '/image' + Math.floor(date.getTime() + date.getSeconds() / 2) + '.png' ==>It works

This worked for me.

Jeyoung-Park commented 2 years ago

still facing the issue. file Download error: Error: Download manager download failed, the file does not downloaded to destination. I got this error message.

I tried everything above but couldn't find the solution -change the sdk version to 29 in rn-fetch-blob -add android:requestLegacyExternalStorage="true" (actually it was already in my project)

Does anybody have other solutions?

Jeyoung-Park commented 2 years ago

I solved it. In my case, there was a problem about filename.

image

As you can see, there are some special characters that are not allowed to use in filenames in android. The characters below are those. \ < > * " : ? \ |

this is my configOptions at first

const configOptions = Platform.select({
            ios: {
                path: RNFetchBlob.fs.dirs.DownloadDir+'/'+file.fileRealName
            },
            android: {
                addAndroidDownloads: {
                    useDownloadManager: true,
                    notification: true,
                    path: RNFetchBlob.fs.dirs.DownloadDir+'/'+file.fileRealName
                }
            }
        })

but there were problems when the filename contains \ < > * " : ? \ |. I think android download manager automatically change the characters above to _ and store in phone

so I changed the filepath like this(replace \ < > * " : ? \ | to _ in filePath

const regExp=/\/|<|>|\*|"|:|\?|\\|\|/g;

        const configOptions = Platform.select({
            ios: {
                path: RNFetchBlob.fs.dirs.DownloadDir+'/'+file.fileRealName.replace(regExp, '_')
            },
            android: {
                addAndroidDownloads: {
                    useDownloadManager: true,
                    notification: true,
                    path: RNFetchBlob.fs.dirs.DownloadDir+'/'+file.fileRealName.replace(regExp, '_')
                }
            }
        })
AnuragTiwari1 commented 2 years ago

I am facing the same issue in case of android only, the files gets download on system but it throws the error [Error: Download manager download failed, the file does not downloaded to destination.]

P.S. i am only facing this issue on Samsung Galaxy M31, OS version: Android Q while other devices(with android 11 and 9) are working fine

ameena-arahman commented 1 year ago

I am facing the same issue in case of android only, the files gets download on system but it throws the error [Error: Download manager download failed, the file does not downloaded to destination.]

P.S. i am only facing this issue on Samsung Galaxy M31, OS version: Android Q while other devices(with android 11 and 9) are working fine

Hi, were you able to find a solution for this? if so can you please mention it here ?

gurpreet-reddotapps commented 1 year ago

@adityakmr7 I am also facing this issue did you find a solution for this?

pankaj-badgujar commented 10 months ago

For me it was the same issue as Jeyoung-Park above, the only difference was I had # in my file name and that was also acting as a special character and causing download manager to error. I simply updated regex of the above in my case to include # const regExp=/\/|<|>|\*|"|:|#|\?|\\|\|/g;