请教一个HarmonyOS 获取文件大小的问题?

文件是从PhotoViewPicker中获取的 如何获取文件大小?

//更换头像 
AppUtil.selectPhoto(1,(data: photoAccessHelper.PhotoSelectResult)=>{ 
 
  let formData = new FormData() 
  let file = fs.openSync(data.photoUris[0], fs.OpenMode.READ_ONLY); 
  try { 
    let stat = fileIo.lstatSync(file.path); 
 
  } catch (e) { 
    Log.debug(e) 
  } 
  let buffer = new ArrayBuffer(4096); 
  let readLen = fs.readSync(file.fd, buffer); 
  console.info('readSync data to file succeed and buffer size is:' + readLen); 
  fs.closeSync(file);

返回后 调用 let stat = fileIo.lstatSync(file.path); 报错 没有找到文件

阅读 478
1 个回答

口味你好,你可以通过photoAccessHelper.getAssets接口获取对应uri的PhotoAsset对象。
这种方式获取的对象读取PhotoKeys.SIZE可以获取文件大小,具体可参考以下代码:

import picker from '@ohos.file.picker'; 
import { photoAccessHelper } from '@kit.MediaLibraryKit'; 
import dataSharePredicates from '@ohos.data.dataSharePredicates'; 
 
let uris: Array<string> = []; 
const context = getContext(this); 
@Entry 
@Component 
struct Index { 
  async photoPick() { 
    let PhotoSelectOptions = new picker.PhotoSelectOptions(); 
    PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; 
    PhotoSelectOptions.maxSelectNumber = 5; 
    let photoPicker = new picker.PhotoViewPicker(); 
    photoPicker.select(PhotoSelectOptions) 
      .then(async (PhotoSelectResult: picker.PhotoSelectResult) => { 
        console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); 
        uris = PhotoSelectResult.photoUris; 
        //调用getAssets接口获取ri对应的PhotoAsset对象,然后通过获取的对象使用PhotoKeys.SIZE获取文件大小 
        this.uriGetAssets() 
      }); 
  } 
  async uriGetAssets() { 
    try { 
      let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); 
      let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); 
      // 配置查询条件,使用PhotoViewPicker选择图片返回的uri进行查询 
      predicates.equalTo('uri', uris[0]); 
      let fetchOption: photoAccessHelper.FetchOptions = { 
        fetchColumns: [], 
        predicates: predicates 
      }; 
      let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption); 
      // 得到uri对应的PhotoAsset对象,读取文件的部分信息 
      const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); 
      console.info('asset size: ', asset.get(photoAccessHelper.PhotoKeys.SIZE)); 
    } catch (error){ 
      console.error('uriGetAssets failed with err: ' + JSON.stringify(error)); 
    } 
  } 
  build() { 
    Column(){ 
      Button("选取图片并获取图片大小").onClick(async () => this.photoPick()) 
    } 
  } 
}
logo
HarmonyOS
子站问答
访问
宣传栏