12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- import RNFS from 'react-native-fs';
- import { unzip } from 'react-native-zip-archive';
- export const downloadToFile = async (
- fileUrl: string,
- fileName: string,
- listener?: (bytesWritten: number, contentLength: number) => void,
- ) => {
- // /storage/emulated/0/Android/data/com.trust.ywx/files/bundles/android/common.android.bundle
- const downloadDest = `${RNFS.ExternalDirectoryPath}/bundles/android/${fileName}`;
- const fileExists = await RNFS.exists(downloadDest);
- if (fileExists) {
- await RNFS.unlink(downloadDest);
- }
- const options = {
- fromUrl: fileUrl,
- toFile: downloadDest,
- progress: (res: any) => {
- listener && listener(res.bytesWritten, res.contentLength);
- console.log(
- `进度: ${((res.bytesWritten / res.contentLength) * 100).toFixed(2)}%`,
- );
- },
- };
- try {
- const res = await RNFS.downloadFile(options).promise;
- console.log('文件已下载到沙盒:', downloadDest, res);
- const exists = await RNFS.exists(downloadDest);
- if (exists) {
- const result = await unzip(
- downloadDest,
- `${RNFS.ExternalDirectoryPath}/bundles/android/`,
- );
- console.log('文件已解压到沙盒:', downloadDest, result);
- }
- return downloadDest;
- } catch (error) {
- console.error('下载失败:', error);
- }
- };
|