#鸿蒙通关秘籍#在HarmonyOS NEXT中如何选择并读取文件内容?

HarmonyOS
7天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
UX白露为霜

使用DocumentViewPicker来选择文件,并通过readContentFromFile方法读取文件内容:

selectFile() {
    let documentPicker = new picker.DocumentViewPicker();
    documentPicker.select().then((result) => {
      if (result.length > 0) {
        this.uploadFilePath = result[0]
        this.msgHistory += "select file: " + this.uploadFilePath + "\r\n";
        this.canUpload = true
      }
    }).catch((e) => {
      this.msgHistory += 'DocumentViewPicker.select failed ' + e.message + "\r\n";
    });
}

readContentFromFile(fileUri: string): ArrayBuffer {
    let buf = new ArrayBuffer(1024 * 4);
    let file = fs.openSync(fileUri, fs.OpenMode.READ_ONLY);
    let readLen = fs.readSync(file.fd, buf, { offset: 0 });
    let result = buf.slice(0, readLen)
    fs.closeSync(file);
    return result
}

以上代码确保文件选择与读取正确执行,为后续文件上传奠定基础。

分享
微博
QQ
微信
回复
7天前
相关问题