DownLoadFileHelper.ets 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import axios, { AxiosProgressEvent } from '@ohos/axios';
  2. import fileIo from '@ohos.file.fs';
  3. import { util } from '@kit.ArkTS';
  4. import { fileUri } from '@kit.CoreFileKit';
  5. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  6. import { image } from '@kit.ImageKit';
  7. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  8. import { YTLog } from '../../../../Index';
  9. export class DownLoadFileHelper {
  10. private cashPaths: string[] = []
  11. private currentIndex: number = 0
  12. //传入需要下载得url数组并下载文件,通过回调函数返回对应cashPaths数组
  13. async loadFiles(urls: string[], finishDownLoad: (cashPaths: string[]) => void) {
  14. let filePath = getContext(this).cacheDir + '/' + util.generateRandomUUID() + '.jpg'
  15. // Download the file. If the file already exists, delete the existing one first.
  16. try {
  17. fileIo.accessSync(filePath);
  18. fileIo.unlinkSync(filePath);
  19. } catch (err) {
  20. }
  21. await axios({
  22. url: urls[this.currentIndex],
  23. method: 'get',
  24. context: getContext(this),
  25. filePath: filePath,
  26. onDownloadProgress: (progressEvent: AxiosProgressEvent): void => {
  27. // console.info("progress: " + progressEvent && progressEvent.loaded && progressEvent.total ?
  28. // Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0)
  29. }
  30. })
  31. this.currentIndex++
  32. this.cashPaths.unshift(filePath)
  33. if (this.currentIndex < urls.length) {
  34. this.loadFiles(urls, finishDownLoad)
  35. } else {
  36. finishDownLoad(this.cashPaths)
  37. }
  38. }
  39. //传入需要保存得cashPaths数组,并通过ShowAssetsCreationDialog保存文件
  40. async saveByShowAssetsCreationDialog(cashPaths: string[], context: Context, success?: () => void) {
  41. const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
  42. const uris = cashPaths.map(item => fileUri.getUriFromPath(item))
  43. try {
  44. // 指定待保存照片的创建选项,包括文件后缀和照片类型,标题和照片子类型可选。
  45. const photoCreationConfigs = uris.map(() => {
  46. const photoCreationConfig: photoAccessHelper.PhotoCreationConfig = {
  47. fileNameExtension: 'jpg',
  48. photoType: photoAccessHelper.PhotoType.IMAGE,
  49. }
  50. return photoCreationConfig
  51. })
  52. // 基于弹窗授权的方式获取媒体库的目标uri。
  53. let desFileUris: Array<string> =
  54. await phAccessHelper.showAssetsCreationDialog(uris, photoCreationConfigs);
  55. let index = 0
  56. while (index < uris.length) {
  57. //通过该uri打开图片
  58. let file = await fileIo.open(desFileUris[index], fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  59. //获取流
  60. const buffer = await this.getFileBuffer(cashPaths[index])
  61. //通过流写入相册
  62. let writeLen = await fileIo.write(file.fd, buffer)
  63. //关流
  64. await fileIo.close(file)
  65. index++
  66. }
  67. success?.()
  68. } catch (err) {
  69. emitter.emit('hide')
  70. }
  71. }
  72. //传入图片地址,转化为流
  73. async getFileBuffer(filePath: string): Promise<ArrayBuffer> {
  74. try {
  75. const imageSource = image.createImageSource(filePath)
  76. let imagePackerApi = image.createImagePacker();
  77. let buffer = await imagePackerApi.packing(imageSource, {
  78. quality: 100,
  79. format: 'image/jpeg'
  80. })
  81. return buffer
  82. } catch (err) {
  83. let error: BusinessError = err as BusinessError;
  84. console.error(`read file failed, errCode:${error.code}, errMessage:${error.message}`);
  85. return Promise.reject(err)
  86. }
  87. }
  88. //须先申请权限ohos.permission.WRITE_IMAGEVIDEO
  89. async saveImgToAssets(cashPaths: string[]) {
  90. try {
  91. let index = 0;
  92. while (index < cashPaths.length) {
  93. //获取当前上下文
  94. //通过accessHelper模块获取accessHelper对象
  95. let accessHelper = photoAccessHelper.getPhotoAccessHelper(getContext())
  96. //指定待创建的文件类型、后缀和创建选项,创建图片或视频资源 返回创建的图片和视频的uri
  97. let uri = await accessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg')
  98. //通过该uri打开图片
  99. let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  100. //获取流
  101. const buffer = await this.getFileBuffer(cashPaths[index])
  102. //通过流写入相册
  103. let writeLen = await fileIo.write(file.fd, buffer)
  104. //关流
  105. await fileIo.close(file)
  106. index++
  107. }
  108. } catch (e) {
  109. YTLog.error(e)
  110. }
  111. }
  112. getType(imgUrl: string) {
  113. return imgUrl.split('.').pop()
  114. }
  115. }