参考如下代码:
import { filePreview } from '@kit.PreviewKit';
import { promptAction } from '@kit.ArkUI';
import fs from '@ohos.file.fs';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import fileUri from '@ohos.file.fileuri';
let fileName: string = 'tt.jpg';
let context = getContext(this);
let fileDir = context.filesDir; // 获取沙箱路径
let uri = ''; // 获取uri
let pathDir = getContext().filesDir;
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Button('1、相册图片写入沙箱')
.onClick(() => {
this.picture()
})
Button('2、预览')
.onClick(async () => {
let result = await filePreview.canPreview(context, uri); // 传入uri,判断是否可预览
console.log('result:' + result)
if (result) {
let previewInfo: filePreview.PreviewInfo = {
title: fileName,
uri: uri,
mimeType: 'image/jpeg'
}
filePreview.openPreview(getContext(this), previewInfo)
.then(() => {
console.log('预览成功')
}); // 打开预览
} else {
promptAction.showToast({
// 不可预览
message: '文件不可预览'
});
}
})
}
.width('100%')
}
.height('100%')
}
async picture() {
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 1;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
let photouri: Array<string> = PhotoSelectResult.photoUris
console.log('photouri[0]:' + photouri[0])
let file = fs.openSync(photouri[0], fs.OpenMode.READ_ONLY)
// 图片保存到沙箱
uri = fileUri.getUriFromPath(pathDir + '/picture2.jpg')
console.log('uri:'+uri)
let file2 = fs.openSync(pathDir + '/picture2.jpg', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
fs.copyFileSync(file.fd, file2.fd)
fs.closeSync(file);
fs.closeSync(file2);
})
}
}