index.uts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* 引入 interface.uts 文件中定义的变量 */
  2. import { ChooseFileOptions, ChooseFileResult, ChooseFile, ChooseFileSync } from '../interface.uts';
  3. /* 引入 unierror.uts 文件中定义的变量 */
  4. import { ChooseFileFailImpl } from '../unierror.uts';
  5. import picker from '@ohos.file.picker'
  6. import { fileIo as fs } from '@kit.CoreFileKit';
  7. import uri from '@ohos.uri'
  8. import { common } from '@kit.AbilityKit';
  9. import { BusinessError } from '@ohos.base'
  10. export const chooseFileFromModule : ChooseFile = function (options : ChooseFileOptions) {
  11. const documentSelectOptions = new picker.DocumentSelectOptions();
  12. // 选择文档的最大数目 暂时只选一个。
  13. documentSelectOptions.maxSelectNumber = 1;
  14. let uris: Array<string> = [];
  15. let context = getContext() as common.Context; // 请确保 getContext(this) 返回结果为 UIAbilityContext
  16. // 创建文件选择器实例
  17. const documentViewPicker = new picker.DocumentViewPicker(context);
  18. documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  19. //文件选择成功后,返回被选中文档的URI结果集。
  20. uris = documentSelectResult;
  21. let uri: string = '';
  22. let filePath: string = '';
  23. let totalSize = 0;
  24. const BUFFER_SIZE = 4096; // 可调整的常量
  25. if(uris.length > 0) {
  26. uri = uris[0]
  27. // 解码中文路径
  28. filePath = decodeURIComponent(uri);
  29. console.info('filePath are:' + filePath);
  30. // 获取描述符 这里需要注意接口权限参数是fs.OpenMode.READ_ONLY。
  31. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  32. // 获取文件大小 更完整的读取示例(循环读取直到文件结束)
  33. let buffer = new ArrayBuffer(BUFFER_SIZE);
  34. while (true) {
  35. let readLen = fs.readSync(file.fd, buffer);
  36. if (readLen <= 0) break; // 读取结束
  37. totalSize += readLen;
  38. // 处理buffer中的数据...
  39. }
  40. fs.closeSync(file);
  41. console.log(`文件总大小: ${totalSize}字节`);
  42. }
  43. console.info('documentViewPicker.select to file succeed and uris are:' + uris);
  44. // 返回数据
  45. const res : ChooseFileResult = {
  46. size: totalSize,
  47. path: filePath,
  48. name: ''
  49. };
  50. options.success?.(res);
  51. options.complete?.(res);
  52. }).catch((err: BusinessError) => {
  53. console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  54. })
  55. }
  56. async function getFileSize(filePath: string): Promise<number> {
  57. try {
  58. const stat = await fileio.stat(filePath)
  59. return stat.size // 返回文件大小(字节)
  60. } catch (err) {
  61. console.error('获取文件大小失败:', err)
  62. return -1
  63. }
  64. }