文档开发者中心
我的
|

HarmonyOS 5

Android开发

调起文件管理器选择文件或图片后如何获取文件的大小

已解决

获取到的路径是    file://docs/storage/Users/currentUser/tesst/1.jpg 或者file://media/Photo/3/IMG_1736734796_002/screenshot_20250113_101816.jpg

收起
自动换行
深色代码主题
复制
let file = fileIo.openSync(path, fileIo.OpenMode.READ_ONLY);
let buffer = new ArrayBuffer(4096);
let readLen = fileIo.readSync(file.fd, buffer);
fileIo.closeSync(file);

上面这个方法读出来是4096kb

点赞
收藏
回复
9
分享
举报
浏览267 编辑于2025-02-21 03:56广东
全部评论
最多点赞
最新发布
最早发布
|
采纳答复
收起
自动换行
深色代码主题
复制
参考我下面的demo:
收起
自动换行
深色代码主题
复制
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import { BusinessError } from '@ohos.base';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { picker } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
  // 定义一个uri数组,用于接收PhotoViewPicker选择图片返回的uri
  @State uris: Array<string> = [];
  context = getContext(this);
  // 调用PhotoViewPicker.select选择图片
  async photoPickerGetUri() {
    try {
      let photoViewPicker = new picker.PhotoViewPicker();
      photoViewPicker.select().then(async (PhotoSelectResult: picker.PhotoSelectResult) => {
        console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' +
        JSON.stringify(PhotoSelectResult));
        this.uris = PhotoSelectResult.photoUris;
        this.uriGetAssets()
      }).catch((err: BusinessError) => {
        console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
    }
  }
  async uriGetAssets() {
    try {
      let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context);
      let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
      // 配置查询条件,使用PhotoViewPicker选择图片返回的uri进行查询
      predicates.equalTo('uri', this.uris[0]);
      let fetchOption: photoAccessHelper.FetchOptions = {
        fetchColumns: [photoAccessHelper.PhotoKeys.WIDTH, photoAccessHelper.PhotoKeys.HEIGHT,
          photoAccessHelper.PhotoKeys.TITLE, photoAccessHelper.PhotoKeys.SIZE, photoAccessHelper.PhotoKeys.DURATION],
        predicates: predicates
      };
      let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> =
        await phAccessHelper.getAssets(fetchOption);
      // 得到uri对应的PhotoAsset对象,读取文件的部分信息
      const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
      console.info('asset displayName: ', asset.displayName);
      console.info('asset uri: ', asset.uri);
      console.info('asset photoType: ', asset.photoType);
      console.info('asset width: ', asset.get(photoAccessHelper.PhotoKeys.WIDTH));
      console.info('asset height: ', asset.get(photoAccessHelper.PhotoKeys.HEIGHT));
      console.info('asset SIZE: ' + asset.get(photoAccessHelper.PhotoKeys.SIZE));
      console.info('asset DURATION: ' + asset.get(photoAccessHelper.PhotoKeys.DURATION));
      // 获取缩略图
      asset.getThumbnail((err, pixelMap) => {
        if (err == undefined) {
          console.info('getThumbnail successful ' + JSON.stringify(pixelMap));
        } else {
          console.error('getThumbnail fail', err);
        }
      });
    } catch (error) {
      console.error('uriGetAssets failed with err: ' + JSON.stringify(error));
    }
  }
  build() {
    Button('获取文件大小').width(100).height(100)
      .onClick(() => {
        this.photoPickerGetUri()
      })
  }
}

日志:

收起
自动换行
深色代码主题
复制
02-22 16:54:34.197   64106-64106   A03D00/com.123...loworld/JSAPP  com.123.helloworld    I     asset uri:  file://media/Photo/2250/VID_1740022650_055/SVID_20250220_113550_1.mp4
02-22 16:54:34.197   64106-64106   A03D00/com.wgg...loworld/JSAPP  com.wgg.helloworld    I     asset photoType:  2
02-22 16:54:34.197   64106-64106   A03D00/com.123...loworld/JSAPP  com.123.helloworld    I     asset width:  580
02-22 16:54:34.197   64106-64106   A03D00/com.123...loworld/JSAPP  com.123.helloworld    I     asset height:  1280
02-22 16:54:34.197   64106-64106   A03D00/com.123...loworld/JSAPP  com.123.helloworld    I     asset SIZE: 2050357
02-22 16:54:34.197   64106-64106   A03D00/com.123...loworld/JSAPP  com.123.helloworld    I     asset DURATION: 12374
展开全部
3
2楼回复于2025-02-22 08:55 来自广东
  • Sunshine Boy
    异步方法有没有办法改成同步 我需要同步拿到大小 异步会导致执行逻辑顺出不对
    2025-02-25 07:12 来自广东
  • 进击的像素回复Sunshine Boy
    加个返回值,然后let size = await func....
    2025-02-25 07:26 来自上海
  • Sunshine Boy回复进击的像素
    我试过返回值也强制要返回Promise<T> 这个类型 不能只返回结果
    2025-02-25 10:26 来自广东

将文件复制到沙箱目录里面,然后就可以读取其大小

收起
自动换行
深色代码主题
复制
import fs from '@ohos.file.fs';
export class test{
  private copySandBoxFileToPub(): void {
    let sanFile: fs.File = null!;
    let pubFile: fs.File = null!;
    let originUploadPath = 'file://docs/storage/Users/currentUser/Documents/temp/testPdf.pdf'
    let targetUploadPath = getContext(this).cacheDir + '/test.pdf';

    sanFile = fs.openSync(originUploadPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    pubFile = fs.openSync(targetUploadPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);

    fs.copyFileSync(sanFile.fd, pubFile.fd);

    // 文件大小:
    console.log("fs.statSync(targetUploadPath).size" + fs.statSync(targetUploadPath).size.toString())
  }
}
4
1楼回复于2025-02-19 11:51 来自广东
  • Sunshine Boy
    sanFile = fs.openSync(originUploadPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 这行代码报错 Error message:Operation not permitted
    2025-02-20 04:10 来自广东
  • 我是大富翁回复Sunshine Boy
    获取文件大小可以使用fs.lstatSync(filePath).size,可参考文档https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-fs-V5#fslstatsync let filePath = pathDir + "/linkToFile"; let fileStat = fs.lstatSync(filePath); console.info("lstat succeed, the size of file is" + fileStat.size); 或者试下这个方法: readFileSize(filesDir: string) { let filePath = filesDir + "/test.txt"; fs.stat(filePath).then((stat: fs.Stat) => { console.info("get file info succeed, the size of file is " + stat.size); }).catch((err: BusinessError) => { console.error("get file info failed with error message: " + err.message + ", error code: " + err.code); }); }
    2025-02-21 02:30 来自广东
  • Sunshine Boy回复我是大富翁
    调用let fileStat = fs.lstatSync(filePath);传入相册返回的路径 会报No such file or directory
    2025-02-21 03:33 来自广东
  • 展开剩余1条回复
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。