按照文档,本地测试:(使用fd和path会闪退)
import picker from '@ohos.file.picker';
import { BusinessError } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
@Entry
@Component
struct DocPickerPage {
@State message: string = 'hello World';
@State uri: Array<string> = []
async selectFile() {
try {
let DocumentSelectOptions = new picker.DocumentSelectOptions();
let documentPicker = new picker.DocumentViewPicker();
documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult: Array<string>) => {
this.uri = DocumentSelectResult
}).catch((err: BusinessError) => {
});
} catch (error) {
}
}
build() {
Row() {
Column() {
Text('选择文件')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
this.selectFile()
})
// select返回的uri权限是只读权限,开发者可以根据结果集中uri做进一步的处理。
// 注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。
Text('获取文件信息')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
let path: string = this.uri[0]
let file = fs.openSync(path, fs.OpenMode.READ_ONLY);
let fileFd = 'fd://' + file.fd
let stat1 = fs.statSync(file.fd);
console.log(`result ==> ${JSON.stringify(stat1)}`);
let stat2 = fs.statSync(fileFd);
console.log(`result ==> ${JSON.stringify(stat2)}`);
let stat3 = fs.statSync(path);
console.log(`result ==> ${JSON.stringify(stat3)}`);
})
}
.width('100%')
}
.height('100%')
}
}
请参考以下demo: