UpdateHelper.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import RNFS from 'react-native-fs';
  2. import { unzip } from 'react-native-zip-archive';
  3. export const downloadToFile = async (
  4. fileUrl: string,
  5. fileName: string,
  6. listener?: (bytesWritten: number, contentLength: number) => void,
  7. ) => {
  8. // /storage/emulated/0/Android/data/com.trust.ywx/files/bundles/android/common.android.bundle
  9. const downloadDest = `${RNFS.ExternalDirectoryPath}/bundles/android/${fileName}`;
  10. const fileExists = await RNFS.exists(downloadDest);
  11. if (fileExists) {
  12. await RNFS.unlink(downloadDest);
  13. }
  14. const options = {
  15. fromUrl: fileUrl,
  16. toFile: downloadDest,
  17. progress: (res: any) => {
  18. listener && listener(res.bytesWritten, res.contentLength);
  19. console.log(
  20. `进度: ${((res.bytesWritten / res.contentLength) * 100).toFixed(2)}%`,
  21. );
  22. },
  23. };
  24. try {
  25. const res = await RNFS.downloadFile(options).promise;
  26. console.log('文件已下载到沙盒:', downloadDest, res);
  27. const exists = await RNFS.exists(downloadDest);
  28. if (exists) {
  29. const result = await unzip(
  30. downloadDest,
  31. `${RNFS.ExternalDirectoryPath}/bundles/android/`,
  32. );
  33. console.log('文件已解压到沙盒:', downloadDest, result);
  34. }
  35. return downloadDest;
  36. } catch (error) {
  37. console.error('下载失败:', error);
  38. }
  39. };