3

Using react-native-fs for download file from url, when download progess percent reached 100%, I will call another function. However, RNFS.downloadFile not keep track the progress correctly.

_downloadFile = () =>{
  const downloadDest = `${RNFS.ExternalDirectoryPath}/Monstro/${((Math.random() * 1000) | 0)}.jpg`;
  let DownloadFileOptions = {
    fromUrl: "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Boothferry_Road%2C_Goole.jpg/220px-Boothferry_Road%2C_Goole.jpg",         
    toFile: downloadDest,           
    begin: this._downloadFileBegin,
    progress: this._downloadFileProgress,
    background:false,
    progressDivider:1
  };

  RNFS.downloadFile(DownloadFileOptions);
}

_downloadFileBegin = () =>{
  console.log("Download Begin");
}

_downloadFileProgress = (data) =>{
  const percentage = ((100 * data.bytesWritten) / data.contentLength) | 0;
  const text = `Progress ${percentage}%`;
  console.log(text);
  if(percentage == 100) //call another function here
}

Not every time console.log in _downloadFileProgress show Progress 100%, so it is harder for me to check the progress. Did I miss out some setting, or there is any other ways to keep track the progress

FeelRightz
  • 2,777
  • 2
  • 38
  • 73

4 Answers4

3

Hi I implement using this by following RNFS npm guidelines

https://www.npmjs.com/package/react-native-fs

For progress bar I used library

React Native Progress Circle

Link for below line of code

downloadFile(options: DownloadFileOptions): { jobId: number, promise: Promise<DownloadResult> }

   type DownloadFileOptions = {
   fromUrl: string;          // URL to download file from
   toFile: string;           // Local filesystem path to save the file to
  headers?: Headers;        // An object of headers to be passed to the server
  background?: boolean;     // Continue the download in the background after the app terminates (iOS only)
  discretionary?: boolean;  // Allow the OS to control the timing and speed of the download to improve perceived performance  (iOS only)
  cacheable?: boolean;      // Whether the download can be stored in the shared NSURLCache (iOS only, defaults to true)
  progressDivider?: number;
  begin?: (res: DownloadBeginCallbackResult) => void;
  progress?: (res: DownloadProgressCallbackResult) => void;
  resumable?: () => void;    // only supported on iOS yet
  connectionTimeout?: number // only supported on Android yet
  readTimeout?: number       // supported on Android and iOS
};

Here I implement above lines of code like this

RNFS.downloadFile({
     fromUrl: encodedfileURL,
     toFile: downloadfilePath,
     //headers
     background: true, **// Continue the download in the background after the app terminates (iOS only)**
     discretionary: true, **// Allow the OS to control the timing and speed of the download to improve perceived performance  (iOS only)**
     cacheable: true, **// Whether the download can be stored in the shared NSURLCache (iOS only, defaults to true)**
  
     begin: (res: DownloadBeginCallbackResult) => {
       console.log("Response begin ===\n\n");
       console.log(res);
     },
     progress: (res: DownloadProgressCallbackResult) => {
      //here you can calculate your progress for file download

       console.log("Response written ===\n\n");
       let progressPercent = (res.bytesWritten / res.contentLength)*100; // to calculate in percentage
       console.log("\n\nprogress===",progressPercent)
       this.setState({ progress: progressPercent.toString() });
       item.downloadProgress = progressPercent;
       console.log(res);
     }
   })
     .promise.then(res => {
       console.log("res for saving file===", res);
       return RNFS.readFile(downloadfilePath, "base64");
})
kaushal
  • 903
  • 10
  • 17
1

RNFS provides a callback when the download completes, try the following:

RNFS.downloadFile(DownloadFileOptions).promise.then((r) => {
               //call another function here
  });
Patrick R
  • 6,621
  • 1
  • 24
  • 27
1

Actually, there is a bug within the react-native-fs library. when you pass the progress function and want to use the download progress to show something on UI, you HAVE TO pass the begin function too.

I said it's a bug because the react-native-fs developers could check it, if consumer developer passed progress and not passed begin they can pass a noop function as a default prop.

const { jobId, promise } = FileSystem.downloadFile({
  fromUrl: resource,
  toFile: `${DOWNLOAD_DIR}/${utils.nameMaker()}.mp3`,
  background: true,
  discretionary: true,
  cacheable: true,
  begin: noop,  // <===== this line I meant
  progress: onProgress,
});

You can read here for more information

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
0

You need to pass this as the progress option in DownloadFileOptions:

progress: (data) => this._downloadFileProgress(data)
tassock
  • 1,633
  • 1
  • 17
  • 32