HarmonyOS 鸿蒙Next 调用三方应用打开文档类
HarmonyOS 鸿蒙Next 调用三方应用打开文档类
在文件是下载到了本地沙箱环境中,如何调用可用得三方应用打开呢。 例如 .docx文件 调用WPS打开等
2 回复
在rawlife下新建一个1.doc,然后执行下面的demo,打开一个doc文件,自带的文档浏览,然后右上角会提示使用其他文件打开,然后下载wps,就可以使用wps打开,看下这样是否满足需求。
import common from '[@ohos](/user/ohos).app.ability.common';
import fs from '[@ohos](/user/ohos).file.fs';
import { filePreview } from '[@kit](/user/kit).PreviewKit';
import { BusinessError } from '[@kit](/user/kit).BasicServicesKit';
import fileUri from '[@ohos](/user/ohos).file.fileuri';
import { picker } from '[@kit](/user/kit).CoreFileKit';
let context = getContext(this) as common.UIAbilityContext;
let uiContext = getContext(this);
let fileInfo: filePreview.PreviewInfo = {
// 文件预览信息,包含了文件标题名、uri以及文件类型(mimeType)
title: '1.doc',
uri: '',
// mimeType: 'application/pdf' // 文件(夹)的媒体资源类型,如text/plain
mimeType: 'application/msword' // 文件(夹)的媒体资源类型,如text/plain
};
function copyFile() {
console.log("copyFile!")
// let documentSelectOptions = new picker.DocumentSelectOptions();
let documentPicker = new picker.DocumentViewPicker();
// let srcFileDescriptor = context.resourceManager.getRawFdSync('蓝牙ble 模式的demo使用说明%E5%85%B3%E8%81%94%E6%96%87%E4%BB%B6.pdf');
let srcFileDescriptor = context.resourceManager.getRawFdSync('1.doc');
//这里填rawfile文件夹下的文件名(包括后缀)
let stat = fs.statSync(srcFileDescriptor.fd)
console.log(`stat isFile:${stat.isFile()}`);
fs.stat(srcFileDescriptor.fd).then((stat: fs.Stat) => {
console.info("get file info succeed, the size of file is " + stat.size);
}).catch((err: BusinessError) => {
console.error("get file info failed with error message: " + err.message + ", error code: " + err.code);
});
// 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例
let pathDir = context.filesDir;
console.log("path:", pathDir)
let dstPath = pathDir + "/1.doc";
let dest = fs.openSync(dstPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
let fileUriTmp = fileUri.getUriFromPath(dstPath);
fileInfo.uri = fileUriTmp;
let bufsize = 4096
let buf = new ArrayBuffer(bufsize)
let off = 0, len = 0, readedLen = 0
while (len = fs.readSync(srcFileDescriptor.fd, buf, { offset: srcFileDescriptor.offset + off, length: bufsize })) {
readedLen += len
fs.writeSync(dest.fd, buf, { offset: off, length: len })
off = off + len
if ((srcFileDescriptor.length - readedLen) < bufsize) {
bufsize = srcFileDescriptor.length - readedLen
}
}
fs.close(dest.fd)
}
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Xlsx {
[@State](/user/State) message: string = '预览';
build() {
Row() {
Column() {
Button('传到沙箱')
.onClick(()=>{
copyFile()
})
Button(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
filePreview.openPreview(uiContext, fileInfo).then(() => {
console.info('openPreview success');
}).catch((err: BusinessError) => {
console.error('openPreview failed, err = ' + err.message);
});
})
}
.width('100%')
}
.height('100%')
}
}