
回复
嗨~我是小L!在鸿蒙开发中,文件分享就像「数字高速公路」——URI和FD两种方式各有优势。今天带你掌握安全高效的分享技巧,让应用间数据交换更流畅~
维度 | URI分享 | FD分享 |
---|---|---|
操作难度 | 简单(系统自动管理权限) | 复杂(需手动管理文件句柄) |
分享单位 | 单个文件 | 单个文件或目录 |
权限时效 | 临时授权(接收方退出即失效) | 永久授权(FD关闭后失效) |
典型场景 | 文本、图片临时分享 | 大文件、目录批量传输 |
import { fileUri, wantConstant } from '@ohos.fileUri';
import { UIAbility, Want } from '@ohos.app.ability';
export default class ShareAbility extends UIAbility {
onWindowStageCreate() {
// 1. 获取文件URI
const imagePath = `${this.context.filesDir}/poster.jpg`;
const uri = fileUri.getUriFromPath(imagePath);
// 2. 创建分享意图(授予读写权限)
const want: Want = {
action: wantConstant.Action.SEND_DATA,
uri: uri,
type: 'image/jpeg',
flags: wantConstant.Flag.AUTH_READ_URI_PERMISSION |
wantConstant.Flag.AUTH_WRITE_URI_PERMISSION
};
// 3. 发起分享
this.context.startAbility(want).then(() => {
console.log('图片分享成功');
});
}
}
export default class ReceiveAbility extends UIAbility {
onNewWant(want: Want) {
if (want.uri) {
const sourceUri = want.uri;
const destPath = `${this.context.filesDir}/received_${Date.now()}.jpg`;
// 读取URI文件并写入本地
fileIo.copySync(sourceUri, destPath);
console.log('文件已保存至:', destPath);
}
}
}
{
"abilities": [
{
"name": ".ShareAbility",
"skills": [
{
"actions": ["ohos.arkui.intent.action.SEND_DATA"],
"uris": [
{
"scheme": "file",
"host": "*",
"path": "/data/storage/el1/*" // 允许分享的路径范围
}
]
}
]
}
]
}
import { fileIO as fs } from '@ohos.fileIO';
import { FileDescriptor } from '@ohos.fs';
function shareDirectory(sourceDir: string) {
// 1. 打开目录获取FD
const fd: FileDescriptor = fs.openSync(sourceDir, fs.OpenMode.READ);
// 2. 创建FD分享数据
const shareData = {
fd: fd,
type: 'directory',
metadata: {
name: 'ProjectFiles',
size: fs.statSync(sourceDir).size
}
};
// 3. 通过自定义通道传递FD(如IPC)
ipc.send('SHARE_FD', shareData);
}
function handleReceivedFD(fd: FileDescriptor) {
// 1. 读取目录下所有文件
const entries = fs.readdirSync(fd);
// 2. 遍历处理文件
entries.forEach((entry) => {
if (entry.isFile()) {
const fileFd = fs.openSync(`${fd.path}/${entry.name}`, fs.OpenMode.READ);
const content = fs.readFileSync(fileFd, 'utf8');
fs.closeSync(fileFd);
}
});
// 3. 关闭FD释放资源
fs.closeSync(fd);
}
files/
目录)
// 分享前加密文件
import { crypto } from '@ohos.security';
async function encryptAndShare(filePath: string) {
const key = crypto.generateKey('AES', 256);
const encryptedData = await crypto.encryptFile(filePath, key);
const uri = fileUri.getUriFromPath(encryptedData.path);
// 分享加密后的URI
shareUri(uri);
}
用户通过鸿蒙「一碰传」将手机中的文件夹快速分享到平板:
// 手机端:通过软总线发送FD
import { distributedBus } from '@ohos.distributedBus';
const bus = distributedBus.create('file_share_channel');
bus.on('receive_fd', (fdData) => {
// 平板端接收FD后处理
handleReceivedFD(fdData.fd);
});
// 平板端:接收并处理FD
function handleReceivedFD(fd: FileDescriptor) {
// 检查是否为允许的分享目录
if (!isAuthorized(fd.path)) {
fs.closeSync(fd);
throw new Error('非法目录');
}
// 执行文件复制逻辑
}
module.json5
声明SEND_DATA
动作,导致分享失败/sdcard/
可能无权访问finally
块中关闭
const fd = fs.openSync(...);
// 使用FD
fs.closeSync(fd);
dup()
复制