How to use the react-native-fs.downloadFile function in react-native-fs

To help you get started, we’ve selected a few react-native-fs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github codeestX / MoeFM / js / middleware / downloader.js View on Github external
async function create(song) {
    let existDir = await RNFS.exists(RNFS.ExternalStorageDirectoryPath + '/MoeFM').then(boolean => boolean);
    if (!existDir) await RNFS.mkdir(RNFS.ExternalStorageDirectoryPath + '/MoeFM');
    let exist = await RNFS.exists(RNFS.ExternalStorageDirectoryPath + '/MoeFM/' + song.title + '.mp3').then(boolean => boolean);
    if (!exist) {
        RNFS.downloadFile({
            fromUrl: song.url,
            toFile: RNFS.ExternalStorageDirectoryPath + '/MoeFM/' + song.title + '.mp3',
            background: true,
            begin: ((res) => beginCallback(res, song)),
            progress: (progressCallback)
        }).promise.then((result) => {
            resultCallback(result);
        }).catch((err) => {
                if(err.description === "cancelled") {
                    // cancelled by user
                }
                console.log(err);
        });
    }
}
github wutongke / react-native-one / Pages / One / OneCell / OneMusicCell.js View on Github external
this.setState({
                loadProcess: text
            })
            console.log(text);
        };

        var begin = ()=> {
            console.log('Download has begun');
        };

        var progressDivider = 1;

        // Random file name needed to force refresh...
        const downloadDest = `${RNFS.DocumentDirectoryPath}/music.mp3`;

        const ret = RNFS.downloadFile({
            fromUrl: url,
            toFile: downloadDest,
            begin,
            progress,
            background,
            progressDivider
        });

        jobId = ret.jobId;

        ret.promise.then(res => {
            this.initSound();
            this.setState({
                loadStatus: loaded,
                loadProcess: ""
            });
github le0zh / gitbook-reader-rn / src / data / bookFiles.js View on Github external
function executeDownloadFlow(DIR, book) {
  const downlosdFileOpt = {
    fromUrl: book.urls.download.epub,
    toFile: `${DIR}/book.epub`,
    background: true,
    progressDivider: 10,
    progress: res => {
      // 下载进度
      console.log(res);
    },
  };

  // 下载
  const downloadRes = RNFS.downloadFile(downlosdFileOpt);

  return downloadRes.promise
    .then(res => {
      // 解压并生成目录文件
      unzip(book.id);

      // 保存下载记录
      saveDownloadItem(book.id, book.title, book.cover.small, res.bytesWritten);

      // 从下载中列表移除
      downloadingBooks.delete(book.id);

      return downloadRes;
    })
    .catch(err => {
      console.warn(err.message);
github jayesbe / react-native-cacheable-image / image.js View on Github external
// If already downloading, cancel the job
                if (this.jobId) {
                    this._stopDownload();
                }

                let downloadOptions = {
                    fromUrl: imageUri,
                    toFile: filePath,
                    background: this.props.downloadInBackground,
                    begin: this.imageDownloadBegin,
                    progress: this.imageDownloadProgress
                };

                // directory exists.. begin download
                let download = RNFS
                .downloadFile(downloadOptions);

                this.downloading = true;
                this.jobId = download.jobId;

                download.promise
                .then((res) => {
                    this.downloading = false;
                    this.jobId = null;

                    switch (res.statusCode) {
                        case 404:
                        case 403:
                            this.setState({cacheable: false, cachedImagePath: null});
                            break;
                        default:
github cllemon / reactNativeDemo / app / common / utils.js View on Github external
export const generateLocalPath = async (url, format) => {
  try {
    const ABSOLUTEPATH = VALUE.ios
      ? REACTNATIVEFS.LibraryDirectoryPath
      : REACTNATIVEFS.ExternalDirectoryPath;
    const STORAGEPATH = `${ABSOLUTEPATH}/${Date.now()}.${format}`;
    const { statusCode } = await REACTNATIVEFS.downloadFile({
      fromUrl: url,
      toFile: STORAGEPATH
    }).promise;
    if (statusCode === 200) return `file://${STORAGEPATH}`;
    return false;
  } catch (error) {
    console.error('生成本地路径异常', error);
  }
};
github m-inan / react-native-music-app / src / scenes / Playlist / Lists.js View on Github external
let { id, list } = items[index]

		dispatch(multipleDownloadLoading(id, true))

		list = list.filter(item => !item.exists)

		list.map(({ videoId }) => dispatch(setFileLoading(videoId, true)))

		for (const item of list) {
			const { videoId } = item
			const toFile = `${RNFS.DocumentDirectoryPath}/${videoId}.mp3`

			const response = await fetch(`${Api.SERVICE_URL}/download/${videoId}`)
			const { audio: fromUrl } = await response.json()

			const { promise } = RNFS.downloadFile({
				fromUrl,
				toFile
			})

			try {
				await promise

				dispatch(setAudioFileExists(id, videoId))
			} catch (error) {
				console.log(error)
			} finally {
				dispatch(setFileLoading(videoId, false))
			}
		}

		dispatch(multipleDownloadLoading(id, false))
github m-inan / react-native-music-app / src / utils / youtube.js View on Github external
const types = ['maxres', 'standard', 'high', 'medium', 'default']

					if (thumbnails) {
						for (const type of types) {
							if (thumbnails[type]) {
								artwork = thumbnails[type].url

								break
							}
						}
					}

					const imageFile = `${RNFS.DocumentDirectoryPath}/${videoId}.jpg`

					if (artwork) {
						await RNFS.downloadFile({
							fromUrl: artwork,
							toFile: imageFile
						})
					}

					const filePath = `${RNFS.DocumentDirectoryPath}/${videoId}.mp3`

					return {
						title,
						videoId,
						exists: await RNFS.exists(filePath),
						artwork: Platform.OS === 'ios' ? imageFile : `file://${imageFile}`,
						source:
							Platform.OS === 'ios' ? `file:/${filePath}` : `file://${filePath}`
					}
				})
github mybigday / react-native-media-player / example / app.js View on Github external
videoUrlList.forEach((url) => {
			RNFS.downloadFile(url, RNFS.DocumentDirectoryPath + "/" + index + ".mp4", () => {
				this.setState({
					current_jobs: this.state.current_jobs + 1
				});
			}, (downloadResult) => {
				if(downloadResult.contentLength == downloadResult.bytesWritten){
					this.setState({
						finished_jobs: this.state.finished_jobs + 1
					});
					this.loadResource();
				}
			});
			index++;
		});
github mohebifar / react-native-ximage / src / Storage.js View on Github external
download(url) {
    return fs.downloadFile(url, this.getFilePath(url));
  }