HarmonyOS 如何根据选中文件url获取文件的大小

如何根据选中文件url获取文件的大小,例如:"file://docs/storage/Users/currentUser/Download/123.txt"

HarmonyOS
9天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get

可以使用fs.stat方法去获取文件的详细属性信息,参考链接:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-fs-V5#fsstat-1

里边包含文件的大小信息

参考demo,在fs.stat之前,要先调用fs.open方法打开文件:

import fs, { Options, ReadTextOptions } from '@ohos.file.fs';
import { common } from '@kit.AbilityKit';
import { picker } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';

@Entry
@Component
struct DocumentPickerSaveDemo {
  @State message: string = 'Hello World';
  private appContext: common.Context = getContext(this);
  private fileDir: string = ''
  @State resultFileDir: string = ''

  createFile(){
    let cacheDir = this.appContext.filesDir;
    this.fileDir = cacheDir + '/HelloWorldlee.txt'
    let file = fs.openSync(this.fileDir)
    let writeLen = fs.writeSync(file.fd, '你好世界!');
    console.info("write data to file succeed and size is:" + writeLen);
    fs.closeSync(file)
  }
  async saveFile(){
    try {
      let documentSaveOptions = new picker.DocumentSaveOptions();
      documentSaveOptions.newFileNames = ['HelloWorld.txt'];
      let documentPicker = new picker.DocumentViewPicker();
      await documentPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
        let uri = documentSaveResult[0];
        this.resultFileDir = uri
        let sanFile = fs.openSync(this.fileDir, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        let pubFile = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        fs.copyFileSync(sanFile.fd, pubFile.fd)

        fs.close(sanFile)
        fs.close(pubFile)
        console.info('DocumentViewPicker.save successfully, documentSaveResult uri: ' + JSON.stringify(documentSaveResult));
      }).catch((err: BusinessError) => {
        console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
      });
      let pubFile = fs.openSync(this.resultFileDir, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
      let buf = new ArrayBuffer(4096);
      fs.readSync(pubFile.fd, buf);
      let str2 =buffer.from(buf).toString('utf-8')
      let readTextOptions: ReadTextOptions = {
        offset: 1,
        // length: 0,
        encoding: 'utf-8'
      };
      /*let stat = fs.statSync(this.resultFileDir);
      readTextOptions.length = stat.size;*/
      let str = fs.readTextSync(this.resultFileDir, readTextOptions);
      console.info("readText succeed:" + str);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err));
    }
  }
  async getFile(){
    let documentSaveOptions = new picker.DocumentSaveOptions();
    let documentPicker = new picker.DocumentViewPicker();
    await documentPicker.select(documentSaveOptions).then((documentSaveResult: Array<string>) => {
      let uri = documentSaveResult[0]
      let file = fs.openSync(uri)
      let filestat = fs.statSync(file.fd)
      console.log('文件大小:' + filestat.size + 'B')
    }).catch((err: BusinessError) => {
      console.log(JSON.stringify(err))
    })
  }
  build() {
    Row() {
      Column({space: 10}) {
        Button('生成文件')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            this.createFile();
            this.saveFile();
          })
        Button('获取文件')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            this.getFile()
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
function uint8ArrayToHexStr(data: Uint8Array): string {
  let hexString = '';
  let i: number;
  for (i = 0; i < data.length; i++) {
    let char = ('00' + data[i].toString(16)).slice(-2);
    hexString += char;
  }
  return hexString;
}
分享
微博
QQ
微信
回复
9天前
相关问题
HarmonyOS 根据后缀获取公共文件
63浏览 • 1回复 待解决
【AGC API 获取文件 URL】报错 403
494浏览 • 1回复 待解决
HarmonyOS 如果获取一个文件大小
93浏览 • 1回复 待解决
如何解决文件中文乱码问题
2945浏览 • 3回复 待解决
如何根据uri读取文件?
3277浏览 • 1回复 待解决
有谁知道如何获取文件大小
1340浏览 • 1回复 待解决
求大佬告知如何读取文件大小
1829浏览 • 1回复 待解决
HarmonyOS 如何判断一个url文件类型
162浏览 • 1回复 待解决