提交 fa9ee14e 编写于 作者: F fengjq

Rectify the ArkTS code specification in filemanager's related files.

Signed-off-by: Nfengjq <fengjunqing@huawei.com>
上级 ed97251d
...@@ -46,8 +46,9 @@ ...@@ -46,8 +46,9 @@
// pages/xxx.ets // pages/xxx.ets
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import buffer from '@ohos.buffer';
function createFile() { createFile() {
// 获取应用文件路径 // 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir; let filesDir = context.filesDir;
...@@ -58,9 +59,10 @@ function createFile() { ...@@ -58,9 +59,10 @@ function createFile() {
let writeLen = fs.writeSync(file.fd, "Try to write str."); let writeLen = fs.writeSync(file.fd, "Try to write str.");
console.info("The length of str is: " + writeLen); console.info("The length of str is: " + writeLen);
// 从文件读取一段内容 // 从文件读取一段内容
let buf = new ArrayBuffer(1024); let arrayBuffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf, { offset: 0 }); let readLen = fs.readSync(file.fd, arrayBuffer, { offset: 0 });
console.info("the content of file: " + String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); let buf = buffer.from(arrayBuffer, 0, readLen);
console.info("the content of file: " + buf.toString());
// 关闭文件 // 关闭文件
fs.closeSync(file); fs.closeSync(file);
} }
...@@ -75,7 +77,7 @@ function createFile() { ...@@ -75,7 +77,7 @@ function createFile() {
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
function readWriteFile() { readWriteFile() {
// 获取应用文件路径 // 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir; let filesDir = context.filesDir;
...@@ -112,7 +114,7 @@ function readWriteFile() { ...@@ -112,7 +114,7 @@ function readWriteFile() {
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
async function readWriteFileWithStream() { async readWriteFileWithStream() {
// 获取应用文件路径 // 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir; let filesDir = context.filesDir;
...@@ -147,7 +149,7 @@ async function readWriteFileWithStream() { ...@@ -147,7 +149,7 @@ async function readWriteFileWithStream() {
```ts ```ts
// 查看文件列表 // 查看文件列表
import fs from '@ohos.file.fs'; import fs, { Filter } from '@ohos.file.fs';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
// 获取应用文件路径 // 获取应用文件路径
...@@ -155,18 +157,20 @@ let context = getContext(this) as common.UIAbilityContext; ...@@ -155,18 +157,20 @@ let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir; let filesDir = context.filesDir;
// 查看文件列表 // 查看文件列表
let options = { getListFile() {
recursion: false, let filter: Filter = {
listNum: 0,
filter: {
suffix: ['.png', '.jpg', '.txt'], // 匹配文件后缀名为'.png','.jpg','.txt' suffix: ['.png', '.jpg', '.txt'], // 匹配文件后缀名为'.png','.jpg','.txt'
displayName: ['test%'], // 匹配文件全名以'test'开头 displayName: ['test%'], // 匹配文件全名以'test'开头
fileSizeOver: 0, // 匹配文件大小大于等于0 fileSizeOver: 0, // 匹配文件大小大于等于0
lastModifiedAfter: new Date(0).getTime(), // 匹配文件最近修改时间在1970年1月1日之后 lastModifiedAfter: new Date(0).getTime(), // 匹配文件最近修改时间在1970年1月1日之后
}, }
} let files = fs.listFileSync(filesDir, {
let files = fs.listFileSync(filesDir, options); recursion: false,
for (let i = 0; i < files.length; i++) { listNum: 0,
console.info(`The name of file: ${files[i]}`); filter: filter
});
for (let i = 0; i < files.length; i++) {
console.info(`The name of file: ${files[i]}`);
}
} }
``` ```
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
调用`backup.getLocalCapabilities()`获取能力文件。 调用`backup.getLocalCapabilities()`获取能力文件。
```js ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
async function getLocalCapabilities() { async function getLocalCapabilities() {
try { try {
...@@ -89,16 +89,21 @@ ...@@ -89,16 +89,21 @@
```ts ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// 创建SessionBackup类的实例用于备份数据 // 创建SessionBackup类的实例用于备份数据
let g_session; let g_session: backup.SessionBackup;
function createSessionBackup() { createSessionBackup() {
let sessionBackup = new backup.SessionBackup({ let sessionBackup = new backup.SessionBackup({
onFileReady: async (err, file) => { onFileReady: (err: BusinessError, file: backup.File) => {
if (err) { if (err) {
console.info('onFileReady err: ' + err); console.info('onFileReady err: ' + err);
} }
try { try {
let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName; let bundlePath = filesDir + '/' + file.bundleName;
if (!fs.accessSync(bundlePath)) { if (!fs.accessSync(bundlePath)) {
fs.mkdirSync(bundlePath); fs.mkdirSync(bundlePath);
} }
...@@ -109,21 +114,21 @@ ...@@ -109,21 +114,21 @@
console.error('onFileReady failed with err: ' + e); console.error('onFileReady failed with err: ' + e);
} }
}, },
onBundleBegin: (err, bundleName) => { onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.info('onBundleBegin err: ' + err); console.info('onBundleBegin err: ' + err);
} else { } else {
console.info('onBundleBegin bundleName: ' + bundleName); console.info('onBundleBegin bundleName: ' + bundleName);
} }
}, },
onBundleEnd: (err, bundleName) => { onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.info('onBundleEnd err: ' + err); console.info('onBundleEnd err: ' + err);
} else { } else {
console.info('onBundleEnd bundleName: ' + bundleName); console.info('onBundleEnd bundleName: ' + bundleName);
} }
}, },
onAllBundlesEnd: (err) => { onAllBundlesEnd: (err: BusinessError) => {
if (err) { if (err) {
console.info('onAllBundlesEnd err: ' + err); console.info('onAllBundlesEnd err: ' + err);
} else { } else {
...@@ -137,12 +142,11 @@ ...@@ -137,12 +142,11 @@
return sessionBackup; return sessionBackup;
} }
async function sessionBackup () async sessionBackup () {
{
g_session = createSessionBackup(); g_session = createSessionBackup();
// 此处可根据backup.getLocalCapabilities()提供的能力文件,选择需要备份的应用 // 此处可根据backup.getLocalCapabilities()提供的能力文件,选择需要备份的应用
// 也可直接根据应用包名称进行备份 // 也可直接根据应用包名称进行备份
const backupApps = [ const backupApps: string[] = [
"com.example.hiworld", "com.example.hiworld",
] ]
await g_session.appendBundles(backupApps); await g_session.appendBundles(backupApps);
...@@ -163,22 +167,21 @@ ...@@ -163,22 +167,21 @@
```ts ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
// 创建SessionRestore类的实例用于恢复数据 // 创建SessionRestore类的实例用于恢复数据
let g_session; let g_session: backup.SessionRestore;
async function publishFile(file) async publishFile(file: backup.File) {
{
await g_session.publishFile({ await g_session.publishFile({
bundleName: file.bundleName, bundleName: file.bundleName,
uri: file.uri uri: file.uri
}); });
} }
function createSessionRestore() { createSessionRestore() {
let sessionRestore = new backup.SessionRestore({ let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => { onFileReady: (err: BusinessError, file: backup.File) => {
if (err) { if (err) {
console.info('onFileReady err: ' + err); console.info('onFileReady err: ' + err);
} }
// 此处开发者请根据实际场景待恢复文件存放位置进行调整 bundlePath // 此处开发者请根据实际场景待恢复文件存放位置进行调整 bundlePath
let bundlePath; let bundlePath: string;
if (!fs.accessSync(bundlePath)) { if (!fs.accessSync(bundlePath)) {
console.info('onFileReady bundlePath err : ' + bundlePath); console.info('onFileReady bundlePath err : ' + bundlePath);
} }
...@@ -188,19 +191,19 @@ ...@@ -188,19 +191,19 @@
publishFile(file); publishFile(file);
console.info('onFileReady success'); console.info('onFileReady success');
}, },
onBundleBegin: (err, bundleName) => { onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.error('onBundleBegin failed with err: ' + err); console.error('onBundleBegin failed with err: ' + err);
} }
console.info('onBundleBegin success'); console.info('onBundleBegin success');
}, },
onBundleEnd: (err, bundleName) => { onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.error('onBundleEnd failed with err: ' + err); console.error('onBundleEnd failed with err: ' + err);
} }
console.info('onBundleEnd success'); console.info('onBundleEnd success');
}, },
onAllBundlesEnd: (err) => { onAllBundlesEnd: (err: BusinessError) => {
if (err) { if (err) {
console.error('onAllBundlesEnd failed with err: ' + err); console.error('onAllBundlesEnd failed with err: ' + err);
} }
...@@ -213,10 +216,9 @@ ...@@ -213,10 +216,9 @@
return sessionRestore; return sessionRestore;
} }
async function restore () async restore01 () {
{
g_session = createSessionRestore(); g_session = createSessionRestore();
const backupApps = [ const backupApps: string[] = [
"com.example.hiworld", "com.example.hiworld",
] ]
// 能力文件的获取方式可以根据开发者实际场景进行调整。此处仅为请求示例 // 能力文件的获取方式可以根据开发者实际场景进行调整。此处仅为请求示例
...@@ -251,21 +253,20 @@ ...@@ -251,21 +253,20 @@
```ts ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
// 创建SessionRestore类的实例用于恢复数据 // 创建SessionRestore类的实例用于恢复数据
let g_session; let g_session: backup.SessionRestore;
async function publishFile(file) async publishFile(file) {
{
await g_session.publishFile({ await g_session.publishFile({
bundleName: file.bundleName, bundleName: file.bundleName,
uri: file.uri uri: file.uri
}); });
} }
function createSessionRestore() { createSessionRestore() {
let sessionRestore = new backup.SessionRestore({ let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => { onFileReady: (err: BusinessError, file: backup.File) => {
if (err) { if (err) {
console.info('onFileReady err: ' + err); console.info('onFileReady err: ' + err);
} }
let bundlePath; let bundlePath: string;
if( file.uri == "/data/storage/el2/restore/bundle.hap" ) if( file.uri == "/data/storage/el2/restore/bundle.hap" )
{ {
// 此处开发者请根据实际场景安装包的存放位置进行调整 // 此处开发者请根据实际场景安装包的存放位置进行调整
...@@ -281,19 +282,19 @@ ...@@ -281,19 +282,19 @@
publishFile(file); publishFile(file);
console.info('onFileReady success'); console.info('onFileReady success');
}, },
onBundleBegin: (err, bundleName) => { onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.error('onBundleBegin failed with err: ' + err); console.error('onBundleBegin failed with err: ' + err);
} }
console.info('onBundleBegin success'); console.info('onBundleBegin success');
}, },
onBundleEnd: (err, bundleName) => { onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) { if (err) {
console.error('onBundleEnd failed with err: ' + err); console.error('onBundleEnd failed with err: ' + err);
} }
console.info('onBundleEnd success'); console.info('onBundleEnd success');
}, },
onAllBundlesEnd: (err) => { onAllBundlesEnd: (err: BusinessError) => {
if (err) { if (err) {
console.error('onAllBundlesEnd failed with err: ' + err); console.error('onAllBundlesEnd failed with err: ' + err);
} }
...@@ -306,10 +307,9 @@ ...@@ -306,10 +307,9 @@
return sessionRestore; return sessionRestore;
} }
async function restore () async restore02 () {
{
g_session = createSessionRestore(); g_session = createSessionRestore();
const backupApps = [ const backupApps: string[] = [
"com.example.hiworld", "com.example.hiworld",
] ]
let fpath = await globalThis.context.filesDir + '/localCapabilities.json'; let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
......
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import request from '@ohos.request'; import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
// 获取应用文件路径 // 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
...@@ -30,29 +31,29 @@ fs.writeSync(file.fd, 'upload file test'); ...@@ -30,29 +31,29 @@ fs.writeSync(file.fd, 'upload file test');
fs.closeSync(file); fs.closeSync(file);
// 上传任务配置项 // 上传任务配置项
let uploadConfig = { let files: Array<request.File> = [
{ filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
]
let data: request.RequestData = { name: 'name', value: 'value' };
let uploadConfig: request.UploadConfig = {
url: 'https://xxx', url: 'https://xxx',
header: { key1: 'value1', key2: 'value2' }, header: { key1: 'value1', key2: 'value2' },
method: 'POST', method: 'POST',
files: [ files: files,
{ filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } data: [ data ]
],
data: [
{ name: 'name', value: 'value' }
]
} }
// 将本地应用文件上传至网络服务器 // 将本地应用文件上传至网络服务器
try { try {
request.uploadFile(context, uploadConfig) request.uploadFile(context, uploadConfig)
.then((uploadTask) => { .then((uploadTask: request.UploadTask) => {
uploadTask.on('complete', (taskStates) => { uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
for (let i = 0; i < taskStates.length; i++) { for (let i = 0; i < taskStates.length; i++) {
console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`); console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
} }
}); });
}) })
.catch((err) => { .catch((err: BusinessError) => {
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
}) })
} catch (err) { } catch (err) {
...@@ -78,6 +79,7 @@ try { ...@@ -78,6 +79,7 @@ try {
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import request from '@ohos.request'; import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
// 获取应用文件路径 // 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
...@@ -87,16 +89,17 @@ try { ...@@ -87,16 +89,17 @@ try {
request.downloadFile(context, { request.downloadFile(context, {
url: 'https://xxxx/xxxx.txt', url: 'https://xxxx/xxxx.txt',
filePath: filesDir + '/xxxx.txt' filePath: filesDir + '/xxxx.txt'
}).then((downloadTask) => { }).then((downloadTask: request.DownloadTask) => {
downloadTask.on('complete', () => { downloadTask.on('complete', () => {
console.info('download complete'); console.info('download complete');
let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
let buf = new ArrayBuffer(1024); let arrayBuffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf); let readLen = fs.readSync(file.fd, arrayBuffer);
console.info(`The content of file: ${String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))}`); let buf = buffer.from(arrayBuffer, 0, readLen);
console.info(`The content of file: ${buf.toString()}`);
fs.closeSync(file); fs.closeSync(file);
}) })
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
}); });
} catch (err) { } catch (err) {
......
...@@ -28,9 +28,10 @@ API的详细介绍请参见[ohos.file.statvfs](../reference/apis/js-apis-file-st ...@@ -28,9 +28,10 @@ API的详细介绍请参见[ohos.file.statvfs](../reference/apis/js-apis-file-st
```ts ```ts
import statvfs from '@ohos.file.statvfs'; import statvfs from '@ohos.file.statvfs';
import { BusinessError } from '@ohos.base';
let path = "/data"; let path = "/data";
statvfs.getFreeSize(path, (err, number) => { statvfs.getFreeSize(path, (err: BusinessError, number: number) => {
if (err) { if (err) {
console.error(`Invoke getFreeSize failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke getFreeSize failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -43,8 +44,9 @@ API的详细介绍请参见[ohos.file.statvfs](../reference/apis/js-apis-file-st ...@@ -43,8 +44,9 @@ API的详细介绍请参见[ohos.file.statvfs](../reference/apis/js-apis-file-st
```ts ```ts
import storageStatistics from "@ohos.file.storageStatistics"; import storageStatistics from "@ohos.file.storageStatistics";
import { BusinessError } from '@ohos.base';
storageStatistics.getCurrentBundleStats((err, bundleStats) => { storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => {
if (err) { if (err) {
console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
......
...@@ -22,6 +22,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ...@@ -22,6 +22,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以
```ts ```ts
import fileAccess from '@ohos.file.fileAccess'; import fileAccess from '@ohos.file.fileAccess';
import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; import fileExtensionInfo from '@ohos.file.fileExtensionInfo';
import { Filter } from '@ohos.file.fs';
``` ```
其中fileAccess提供了文件基础操作的API,fileExtensionInfo提供了应用开发的关键结构体。 其中fileAccess提供了文件基础操作的API,fileExtensionInfo提供了应用开发的关键结构体。
...@@ -33,7 +34,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ...@@ -33,7 +34,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以
```ts ```ts
// 创建连接系统内所有文件管理服务端的helper对象 // 创建连接系统内所有文件管理服务端的helper对象
let fileAccessHelperAllServer = null; let fileAccessHelperAllServer: fileAccess.FileAccessHelper;
createFileAccessHelper() { createFileAccessHelper() {
try { // this.context是EntryAbility传过来的Context try { // this.context是EntryAbility传过来的Context
fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context); fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context);
...@@ -44,23 +45,23 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ...@@ -44,23 +45,23 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以
console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
} }
} }
async getRoots() { async getRoots() {
let rootIterator = null; let rootIterator: fileAccess.RootIterator;
let rootInfos = []; let rootInfos: fileAccess.RootInfo[] = [];
let isDone = false; let isDone: boolean = false;
try { try {
rootIterator = await fileAccessHelperAllServer.getRoots(); rootIterator = await fileAccessHelperAllServer.getRoots();
if (!rootIterator) { if (!rootIterator) {
console.error("getRoots interface returns an undefined object"); console.error("getRoots interface returns an undefined object");
return; return;
} }
while (!isDone) { while (!isDone) {
let result = rootIterator.next(); let result = rootIterator.next();
console.info("next result = " + JSON.stringify(result)); console.info("next result = " + JSON.stringify(result));
isDone = result.done; isDone = result.done;
if (!isDone) if (!isDone)
rootinfos.push(result.value); rootInfos.push(result.value);
} }
} catch (error) { } catch (error) {
console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message); console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
} }
...@@ -74,10 +75,10 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ...@@ -74,10 +75,10 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以
```ts ```ts
// 从根目录开始 // 从根目录开始
let rootInfo = rootinfos[0]; let rootInfo = rootInfos[0];
let fileInfos = []; let fileInfos: fileAccess.FileInfo[] = [];
let isDone = false; let isDone: boolean = false;
let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件 let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件
try { try {
let fileIterator = rootInfo.listFile(); // 遍历设备rootinfos[0]的根目录,返回迭代器对象 let fileIterator = rootInfo.listFile(); // 遍历设备rootinfos[0]的根目录,返回迭代器对象
// let fileIterator = rootInfo.scanFile(filter); // 过滤设备rootinfos[0]满足指定条件的文件信息,返回迭代对象 // let fileIterator = rootInfo.scanFile(filter); // 过滤设备rootinfos[0]满足指定条件的文件信息,返回迭代对象
...@@ -98,9 +99,9 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ...@@ -98,9 +99,9 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以
// 从指定的目录开始 // 从指定的目录开始
let fileInfoDir = fileInfos[0]; // fileInfoDir 表示某个目录信息 let fileInfoDir = fileInfos[0]; // fileInfoDir 表示某个目录信息
let subFileInfos = []; let subFileInfos: fileAccess.FileInfo[] = [];
let isDone = false; let isDone: boolean = false;
let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件 let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件
try { try {
let fileIterator = fileInfoDir.listFile(); // 遍历特定的目录fileinfo,返回迭代器对象 let fileIterator = fileInfoDir.listFile(); // 遍历特定的目录fileinfo,返回迭代器对象
// let fileIterator = rootInfo.scanFile(filter); // 过滤特定的目录fileinfo,返回迭代器对象 // let fileIterator = rootInfo.scanFile(filter); // 过滤特定的目录fileinfo,返回迭代器对象
...@@ -113,7 +114,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ...@@ -113,7 +114,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以
console.info("next result = " + JSON.stringify(result)); console.info("next result = " + JSON.stringify(result));
isDone = result.done; isDone = result.done;
if (!isDone) if (!isDone)
subfileInfos.push(result.value); subFileInfos.push(result.value);
} }
} catch (error) { } catch (error) {
console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message); console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
...@@ -128,9 +129,9 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ...@@ -128,9 +129,9 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以
// 创建文件 // 创建文件
// 示例代码sourceUri是Download目录的fileinfo中的URI // 示例代码sourceUri是Download目录的fileinfo中的URI
// 开发者应根据自己实际获取fileinfo的URI进行开发 // 开发者应根据自己实际获取fileinfo的URI进行开发
let sourceUri = "file://docs/storage/Users/currentUser/Download"; let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
let displayName = "file1"; let displayName: string = "file1";
let fileUri = null; let fileUri: string;
try { try {
// fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取
fileUri = await fileAccessHelper.createFile(sourceUri, displayName); fileUri = await fileAccessHelper.createFile(sourceUri, displayName);
......
...@@ -14,11 +14,12 @@ ...@@ -14,11 +14,12 @@
```ts ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
let context = ...; // 获取设备A的UIAbilityContext信息
let pathDir = context.distributedFilesDir; let context = getContext(this) as common.UIAbilityContext; // 获取设备A的UIAbilityContext信息
let pathDir: string = context.distributedFilesDir;
// 获取分布式目录的文件路径 // 获取分布式目录的文件路径
let filePath = pathDir + '/test.txt'; let filePath: string = pathDir + '/test.txt';
try { try {
// 在分布式目录下创建文件 // 在分布式目录下创建文件
...@@ -37,23 +38,26 @@ ...@@ -37,23 +38,26 @@
```ts ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import buffer from '@ohos.buffer';
let context = ...; // 获取设备B的UIAbilityContext信息 let context = getContext(this) as common.UIAbilityContext; // 获取设备B的UIAbilityContext信息
let pathDir = context.distributedFilesDir; let pathDir: string = context.distributedFilesDir;
// 获取分布式目录的文件路径 // 获取分布式目录的文件路径
let filePath = pathDir + '/test.txt'; let filePath: string = pathDir + '/test.txt';
try { try {
// 打开分布式目录下的文件 // 打开分布式目录下的文件
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
// 定义接收读取数据的缓存 // 定义接收读取数据的缓存
let buffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
// 读取文件的内容,返回值是读取到的字节个数 // 读取文件的内容,返回值是读取到的字节个数
let num = fs.readSync(file.fd, buffer, { let num = fs.readSync(file.fd, arrayBuffer, {
offset: 0 offset: 0
}); });
// 打印读取到的文件数据 // 打印读取到的文件数据
console.info('read result: ' + String.fromCharCode.apply(null, new Uint8Array(buffer.slice(0, num)))); let buf = buffer.from(arrayBuffer, 0, num);
console.info('read result: ' + buf.toString());
} catch (err) { } catch (err) {
console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`); console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`);
} }
......
...@@ -55,8 +55,9 @@ ...@@ -55,8 +55,9 @@
```ts ```ts
import CommonEvent from '@ohos.commonEventManager'; import CommonEvent from '@ohos.commonEventManager';
import volumeManager from '@ohos.file.volumeManager'; import volumeManager from '@ohos.file.volumeManager';
import { BusinessError } from '@ohos.base';
const subscribeInfo = {
const subscribeInfo: CommonEvent.CommonEventSubscribeInfo = {
events: [ events: [
"usual.event.data.VOLUME_REMOVED", "usual.event.data.VOLUME_REMOVED",
"usual.event.data.VOLUME_UNMOUNTED", "usual.event.data.VOLUME_UNMOUNTED",
...@@ -71,11 +72,11 @@ ...@@ -71,11 +72,11 @@
3. 收到广播通知后获取卷设备信息。 3. 收到广播通知后获取卷设备信息。
```ts ```ts
CommonEvent.subscribe(subscriber, function (err, data) { CommonEvent.subscribe(subscriber, (err: BusinessError, data: CommonEvent.CommonEventData) => {
if (data.event === 'usual.event.data.VOLUME_MOUNTED') { if (data.event === 'usual.event.data.VOLUME_MOUNTED') {
// 开发者可以通过广播传递的卷设备信息来管理卷设备 // 开发者可以通过广播传递的卷设备信息来管理卷设备
let volId = data.parameters.id; let volId: string = data.parameters.id;
volumeManager.getVolumeById(volId, function(error, vol) { volumeManager.getVolumeById(volId, (error: BusinessError, vol: volumeManager.Volume) => {
if (error) { if (error) {
console.error('volumeManager getVolumeById failed'); console.error('volumeManager getVolumeById failed');
} else { } else {
......
...@@ -18,33 +18,36 @@ save接口会将文件保存在文件管理器,而不是图库。 ...@@ -18,33 +18,36 @@ save接口会将文件保存在文件管理器,而不是图库。
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import photoAccessHelper from '@ohos.file.photoAccessHelper'; import photoAccessHelper from '@ohos.file.photoAccessHelper';
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
import common from '@ohos.app.ability.common';
import image from '@ohos.multimedia.image';
import { BusinessError } from '@ohos.base';
``` ```
2. 获取设备里第一张图片的缩略图。注意:在执行这一步之前,要先确保设备里至少有一张图片。 2. 获取设备里第一张图片的缩略图。注意:在执行这一步之前,要先确保设备里至少有一张图片。
```ts ```ts
const context = getContext(this); let context = getContext(this) as common.UIAbilityContext;
let photoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
let pixelmapArrayBuffer; let pixelmapArrayBuffer: ArrayBuffer;
async getPixelmap() { async getPixelmap() {
try { try {
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = { let fetchOption: photoAccessHelper.FetchOptions = {
fetchColumns: [], fetchColumns: [],
predicates: predicates predicates: predicates
}; };
let fetchResult = await photoAccessHelper.getAssets(fetchOption); let fetchResult = await phAccessHelper.getAssets(fetchOption);
console.info('[picker] getThumbnail fetchResult: ' + fetchResult); console.info('[picker] getThumbnail fetchResult: ' + fetchResult);
const asset = await fetchResult.getFirstObject(); const asset = await fetchResult.getFirstObject();
console.info('[picker] getThumbnail asset displayName = ', asset.displayName); console.info('[picker] getThumbnail asset displayName = ', asset.displayName);
asset.getThumbnail().then((pixelMap) => { asset.getThumbnail().then((pixelMap: image.PixelMap) => {
let pixelBytesNumber = pixelMap.getPixelBytesNumber(); let pixelBytesNumber = pixelMap.getPixelBytesNumber();
const readBuffer = new ArrayBuffer(pixelBytesNumber); const readBuffer = new ArrayBuffer(pixelBytesNumber);
pixelMap.readPixelsToBuffer(readBuffer).then(() => { pixelMap.readPixelsToBuffer(readBuffer).then(() => {
pixelmapArrayBuffer = readBuffer; pixelmapArrayBuffer = readBuffer;
}) })
}).catch((err) => { }).catch((err: BusinessError) => {
console.error('[picker] getThumbnail failed with error: ' + err); console.error('[picker] getThumbnail failed with error: ' + err);
}); });
} catch (error) { } catch (error) {
...@@ -58,7 +61,7 @@ save接口会将文件保存在文件管理器,而不是图库。 ...@@ -58,7 +61,7 @@ save接口会将文件保存在文件管理器,而不是图库。
save返回的uri权限是读写权限,可以根据结果集里面的uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 save返回的uri权限是读写权限,可以根据结果集里面的uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。
```ts ```ts
let uris = null; let uris: string;
async photoViewPickerSave() { async photoViewPickerSave() {
try { try {
const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建文件管理器保存选项实例 const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建文件管理器保存选项实例
...@@ -85,7 +88,7 @@ save接口会将文件保存在文件管理器,而不是图库。 ...@@ -85,7 +88,7 @@ save接口会将文件保存在文件管理器,而不是图库。
然后,通过fd使用[fs.write](../reference/apis/js-apis-file-fs.md#fswrite)接口对这个文件进行编辑修改,编辑修改完成后关闭fd。 然后,通过fd使用[fs.write](../reference/apis/js-apis-file-fs.md#fswrite)接口对这个文件进行编辑修改,编辑修改完成后关闭fd。
```ts ```ts
async writeOnly(uri) { async writeOnly(uri: string) {
try { try {
let file = fs.openSync(uri, fs.OpenMode.WRITE_ONLY); let file = fs.openSync(uri, fs.OpenMode.WRITE_ONLY);
let writeLen = await fs.write(file.fd, pixelmapArrayBuffer); let writeLen = await fs.write(file.fd, pixelmapArrayBuffer);
...@@ -104,6 +107,7 @@ save接口会将文件保存在文件管理器,而不是图库。 ...@@ -104,6 +107,7 @@ save接口会将文件保存在文件管理器,而不是图库。
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
``` ```
2. 创建文档保存选项实例。 2. 创建文档保存选项实例。
...@@ -119,12 +123,12 @@ save接口会将文件保存在文件管理器,而不是图库。 ...@@ -119,12 +123,12 @@ save接口会将文件保存在文件管理器,而不是图库。
</br>save返回的uri权限是读写权限,可以根据结果集中uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 </br>save返回的uri权限是读写权限,可以根据结果集中uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。
```ts ```ts
let uris = null; let uris: Array<string>;
const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例 const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例
documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => { documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
uris = documentSaveResult; uris = documentSaveResult;
console.info('documentViewPicker.save to file succeed and uris are:' + uris); console.info('documentViewPicker.save to file succeed and uris are:' + uris);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
...@@ -151,6 +155,7 @@ save接口会将文件保存在文件管理器,而不是图库。 ...@@ -151,6 +155,7 @@ save接口会将文件保存在文件管理器,而不是图库。
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
``` ```
2. 创建音频保存选项实例。 2. 创建音频保存选项实例。
...@@ -165,12 +170,12 @@ save接口会将文件保存在文件管理器,而不是图库。 ...@@ -165,12 +170,12 @@ save接口会将文件保存在文件管理器,而不是图库。
</br>save返回的uri权限是读写权限,可以根据结果集中uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 </br>save返回的uri权限是读写权限,可以根据结果集中uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。
```ts ```ts
let uri = null; let uri: string;
const audioViewPicker = new picker.AudioViewPicker(); const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => { audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array<string>) => {
uri = audioSelectResult[0]; uri = audioSelectResult[0];
console.info('audioViewPicker.save to file succeed and uri is:' + uri); console.info('audioViewPicker.save to file succeed and uri is:' + uri);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
``` ```
2. 创建图库选择选项实例。 2. 创建图库选择选项实例。
...@@ -38,12 +39,12 @@ ...@@ -38,12 +39,12 @@
</br>select返回的uri权限是只读权限,可以根据结果集中uri进行读取文件数据操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 </br>select返回的uri权限是只读权限,可以根据结果集中uri进行读取文件数据操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。
```ts ```ts
let uris = null; let uris: Array<string>;
const photoViewPicker = new picker.PhotoViewPicker(); const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => { photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
uris = photoSelectResult.photoUris; uris = photoSelectResult.photoUris;
console.info('photoViewPicker.select to file succeed and uris are:' + uris); console.info('photoViewPicker.select to file succeed and uris are:' + uris);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
...@@ -71,6 +72,8 @@ ...@@ -71,6 +72,8 @@
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
``` ```
2. 创建文档选择选项实例。 2. 创建文档选择选项实例。
...@@ -89,12 +92,12 @@ ...@@ -89,12 +92,12 @@
</br>例如通过[文件管理接口](../reference/apis/js-apis-file-fs.md)根据uri获取部分文件属性信息,比如文件大小、访问时间、修改时间等。如有获取文件名称需求,请暂时使用[startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md)获取。 </br>例如通过[文件管理接口](../reference/apis/js-apis-file-fs.md)根据uri获取部分文件属性信息,比如文件大小、访问时间、修改时间等。如有获取文件名称需求,请暂时使用[startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md)获取。
```ts ```ts
let uris = null; let uris: Array<string>;
const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例 const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例
documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
uris = documentSelectResult; uris = documentSelectResult;
console.info('documentViewPicker.select to file succeed and uris are:' + uris); console.info('documentViewPicker.select to file succeed and uris are:' + uris);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
...@@ -104,7 +107,7 @@ ...@@ -104,7 +107,7 @@
> 目前DocumentSelectOptions功能不完整, 如需获取文件名称,请使用startAbilityForResult接口。 > 目前DocumentSelectOptions功能不完整, 如需获取文件名称,请使用startAbilityForResult接口。
```ts ```ts
let config = { let config: Want = {
action: 'ohos.want.action.OPEN_FILE', action: 'ohos.want.action.OPEN_FILE',
parameters: { parameters: {
startMode: 'choose', startMode: 'choose',
...@@ -149,6 +152,7 @@ ...@@ -149,6 +152,7 @@
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
``` ```
2. 创建音频选择选项实例。 2. 创建音频选择选项实例。
...@@ -168,12 +172,12 @@ ...@@ -168,12 +172,12 @@
> 目前AudioSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。 > 目前AudioSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。
```ts ```ts
let uri = null; let uri: string;
const audioViewPicker = new picker.AudioViewPicker(); const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.select(audioSelectOptions).then(audioSelectResult => { audioViewPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
uri = audioSelectResult[0]; uri = audioSelectResult[0];
console.info('audioViewPicker.select to file succeed and uri is:' + uri); console.info('audioViewPicker.select to file succeed and uri is:' + uri);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
......
...@@ -26,16 +26,18 @@ API详细介绍请参见[ohos.file.securityLabel](../reference/apis/js-apis-file ...@@ -26,16 +26,18 @@ API详细介绍请参见[ohos.file.securityLabel](../reference/apis/js-apis-file
```ts ```ts
import securityLabel from '@ohos.file.securityLabel'; import securityLabel from '@ohos.file.securityLabel';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
// 获取需要设备数据等级的文件沙箱路径 // 获取需要设备数据等级的文件沙箱路径
let context = ...; // 获取UIAbilityContext信息 let context = getContext(this) as common.UIAbilityContext; // 获取UIAbilityContext信息
let pathDir = context.filesDir; let pathDir = context.filesDir;
let filePath = pathDir + '/test.txt'; let filePath = pathDir + '/test.txt';
// 设置文件的数据等级为s0 // 设置文件的数据等级为s0
securityLabel.setSecurityLabel(filePath, 's0').then(() => { securityLabel.setSecurityLabel(filePath, 's0').then(() => {
console.info('Succeeded in setSecurityLabeling.'); console.info('Succeeded in setSecurityLabeling.');
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`); console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -54,6 +54,8 @@ ...@@ -54,6 +54,8 @@
import window from '@ohos.window'; import window from '@ohos.window';
import wantConstant from '@ohos.app.ability.wantConstant'; import wantConstant from '@ohos.app.ability.wantConstant';
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
...@@ -61,7 +63,7 @@ ...@@ -61,7 +63,7 @@
let filePath = this.context.filesDir + '/test.txt'; let filePath = this.context.filesDir + '/test.txt';
// 将沙箱路径转换为uri // 将沙箱路径转换为uri
let uri = fileuri.getUriFromPath(filePath); let uri = fileuri.getUriFromPath(filePath);
let want = { let want: Want = {
// 配置被分享文件的读写权限,例如对被分享应用进行读写授权 // 配置被分享文件的读写权限,例如对被分享应用进行读写授权
flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
// 配置分享应用的隐式拉起规则 // 配置分享应用的隐式拉起规则
...@@ -73,7 +75,7 @@ ...@@ -73,7 +75,7 @@
.then(() => { .then(() => {
console.info('Invoke getCurrentBundleStats succeeded.'); console.info('Invoke getCurrentBundleStats succeeded.');
}) })
.catch((err) => { .catch((err: BusinessError) => {
console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
}); });
} }
...@@ -120,10 +122,11 @@ ...@@ -120,10 +122,11 @@
```ts ```ts
// xxx.ets // xxx.ets
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import Want from '@ohos.app.ability.Want';
function getShareFile() { function getShareFile() {
try { try {
let want = ...; // 获取分享方传递过来的want信息 let want: Want = ...; // 获取分享方传递过来的want信息
// 从want信息中获取uri字段 // 从want信息中获取uri字段
let uri = want.uri; let uri = want.uri;
......
...@@ -8,8 +8,9 @@ ...@@ -8,8 +8,9 @@
## 导入模块 ## 导入模块
```js ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
import { BusinessError } from '@ohos.base';
``` ```
## PhotoViewPicker ## PhotoViewPicker
...@@ -47,15 +48,15 @@ select(option?: PhotoSelectOptions) : Promise&lt;PhotoSelectResult&gt; ...@@ -47,15 +48,15 @@ select(option?: PhotoSelectOptions) : Promise&lt;PhotoSelectResult&gt;
**示例:** **示例:**
```ts ```ts
async function example() { async example01() {
try { try {
let PhotoSelectOptions = new picker.PhotoSelectOptions(); let PhotoSelectOptions = new picker.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 5; PhotoSelectOptions.maxSelectNumber = 5;
let photoPicker = new picker.PhotoViewPicker(); let photoPicker = new picker.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => { photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: picker.PhotoSelectResult) => {
console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
}).catch((err) => { }).catch((err: BusinessError) => {
console.error('PhotoViewPicker.select failed with err: ' + err); console.error('PhotoViewPicker.select failed with err: ' + err);
}); });
} catch (err) { } catch (err) {
...@@ -82,13 +83,13 @@ select(option: PhotoSelectOptions, callback: AsyncCallback&lt;PhotoSelectResult& ...@@ -82,13 +83,13 @@ select(option: PhotoSelectOptions, callback: AsyncCallback&lt;PhotoSelectResult&
**示例:** **示例:**
```ts ```ts
async function example() { async example02() {
try { try {
let PhotoSelectOptions = new picker.PhotoSelectOptions(); let PhotoSelectOptions = new picker.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 5; PhotoSelectOptions.maxSelectNumber = 5;
let photoPicker = new picker.PhotoViewPicker(); let photoPicker = new picker.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions, (err, PhotoSelectResult) => { photoPicker.select(PhotoSelectOptions, (err: BusinessError, PhotoSelectResult: picker.PhotoSelectResult) => {
if (err) { if (err) {
console.error('PhotoViewPicker.select failed with err: ' + err); console.error('PhotoViewPicker.select failed with err: ' + err);
return; return;
...@@ -118,10 +119,10 @@ select(callback: AsyncCallback&lt;PhotoSelectResult&gt;) : void ...@@ -118,10 +119,10 @@ select(callback: AsyncCallback&lt;PhotoSelectResult&gt;) : void
**示例:** **示例:**
```ts ```ts
async function example() { async example03() {
try { try {
let photoPicker = new picker.PhotoViewPicker(); let photoPicker = new picker.PhotoViewPicker();
photoPicker.select((err, PhotoSelectResult) => { photoPicker.select((err: BusinessError, PhotoSelectResult: picker.PhotoSelectResult) => {
if (err) { if (err) {
console.error('PhotoViewPicker.select failed with err: ' + err); console.error('PhotoViewPicker.select failed with err: ' + err);
return; return;
...@@ -157,14 +158,14 @@ save(option?: PhotoSaveOptions) : Promise&lt;Array&lt;string&gt;&gt; ...@@ -157,14 +158,14 @@ save(option?: PhotoSaveOptions) : Promise&lt;Array&lt;string&gt;&gt;
**示例:** **示例:**
```ts ```ts
async function example() { async example04() {
try { try {
let PhotoSaveOptions = new picker.PhotoSaveOptions(); let PhotoSaveOptions = new picker.PhotoSaveOptions();
PhotoSaveOptions.newFileNames = ['PhotoViewPicker01.jpg', 'PhotoViewPicker01.mp4']; PhotoSaveOptions.newFileNames = ['PhotoViewPicker01.jpg', 'PhotoViewPicker01.mp4'];
let photoPicker = new picker.PhotoViewPicker(); let photoPicker = new picker.PhotoViewPicker();
photoPicker.save(PhotoSaveOptions).then((PhotoSaveResult) => { photoPicker.save(PhotoSaveOptions).then((PhotoSaveResult: Array<string>) => {
console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult));
}).catch((err) => { }).catch((err: BusinessError) => {
console.error('PhotoViewPicker.save failed with err: ' + err); console.error('PhotoViewPicker.save failed with err: ' + err);
}); });
} catch (err) { } catch (err) {
...@@ -191,12 +192,12 @@ save(option: PhotoSaveOptions, callback: AsyncCallback&lt;Array&lt;string&gt;&gt ...@@ -191,12 +192,12 @@ save(option: PhotoSaveOptions, callback: AsyncCallback&lt;Array&lt;string&gt;&gt
**示例:** **示例:**
```ts ```ts
async function example() { async example05() {
try { try {
let PhotoSaveOptions = new picker.PhotoSaveOptions(); let PhotoSaveOptions = new picker.PhotoSaveOptions();
PhotoSaveOptions.newFileNames = ['PhotoViewPicker02.jpg','PhotoViewPicker02.mp4']; PhotoSaveOptions.newFileNames = ['PhotoViewPicker02.jpg','PhotoViewPicker02.mp4'];
let photoPicker = new picker.PhotoViewPicker(); let photoPicker = new picker.PhotoViewPicker();
photoPicker.save(PhotoSaveOptions, (err, PhotoSaveResult) => { photoPicker.save(PhotoSaveOptions, (err: BusinessError, PhotoSaveResult: Array<string>) => {
if (err) { if (err) {
console.error('PhotoViewPicker.save failed with err: ' + err); console.error('PhotoViewPicker.save failed with err: ' + err);
return; return;
...@@ -226,10 +227,10 @@ save(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void ...@@ -226,10 +227,10 @@ save(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void
**示例:** **示例:**
```ts ```ts
async function example() { async example06() {
try { try {
let photoPicker = new picker.PhotoViewPicker(); let photoPicker = new picker.PhotoViewPicker();
photoPicker.save((err, PhotoSaveResult) => { photoPicker.save((err: BusinessError, PhotoSaveResult: Array<string>) => {
if (err) { if (err) {
console.error('PhotoViewPicker.save failed with err: ' + err); console.error('PhotoViewPicker.save failed with err: ' + err);
return; return;
...@@ -277,13 +278,13 @@ select(option?: DocumentSelectOptions) : Promise&lt;Array&lt;string&gt;&gt; ...@@ -277,13 +278,13 @@ select(option?: DocumentSelectOptions) : Promise&lt;Array&lt;string&gt;&gt;
**示例:** **示例:**
```ts ```ts
async function example() { async example07() {
try { try {
let DocumentSelectOptions = new picker.DocumentSelectOptions(); let DocumentSelectOptions = new picker.DocumentSelectOptions();
let documentPicker = new picker.DocumentViewPicker(); let documentPicker = new picker.DocumentViewPicker();
documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => { documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult: Array<string>) => {
console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
}).catch((err) => { }).catch((err: BusinessError) => {
console.error('DocumentViewPicker.select failed with err: ' + err); console.error('DocumentViewPicker.select failed with err: ' + err);
}); });
} catch (err) { } catch (err) {
...@@ -310,11 +311,11 @@ select(option: DocumentSelectOptions, callback: AsyncCallback&lt;Array&lt;string ...@@ -310,11 +311,11 @@ select(option: DocumentSelectOptions, callback: AsyncCallback&lt;Array&lt;string
**示例:** **示例:**
```ts ```ts
async function example() { async example08() {
try { try {
let DocumentSelectOptions = new picker.DocumentSelectOptions(); let DocumentSelectOptions = new picker.DocumentSelectOptions();
let documentPicker = new picker.DocumentViewPicker(); let documentPicker = new picker.DocumentViewPicker();
documentPicker.select(DocumentSelectOptions, (err, DocumentSelectResult) => { documentPicker.select(DocumentSelectOptions, (err: BusinessError, DocumentSelectResult: Array<string>) => {
if (err) { if (err) {
console.error('DocumentViewPicker.select failed with err: ' + err); console.error('DocumentViewPicker.select failed with err: ' + err);
return; return;
...@@ -344,10 +345,10 @@ select(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void ...@@ -344,10 +345,10 @@ select(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void
**示例:** **示例:**
```ts ```ts
async function example() { async example09() {
try { try {
let documentPicker = new picker.DocumentViewPicker(); let documentPicker = new picker.DocumentViewPicker();
documentPicker.select((err, DocumentSelectResult) => { documentPicker.select((err: BusinessError, DocumentSelectResult: Array<string>) => {
if (err) { if (err) {
console.error('DocumentViewPicker.select failed with err: ' + err); console.error('DocumentViewPicker.select failed with err: ' + err);
return; return;
...@@ -384,14 +385,14 @@ save(option?: DocumentSaveOptions) : Promise&lt;Array&lt;string&gt;&gt; ...@@ -384,14 +385,14 @@ save(option?: DocumentSaveOptions) : Promise&lt;Array&lt;string&gt;&gt;
**示例:** **示例:**
```ts ```ts
async function example() { async example10() {
try { try {
let DocumentSaveOptions = new picker.DocumentSaveOptions(); let DocumentSaveOptions = new picker.DocumentSaveOptions();
DocumentSaveOptions.newFileNames = ['DocumentViewPicker01.txt']; DocumentSaveOptions.newFileNames = ['DocumentViewPicker01.txt'];
let documentPicker = new picker.DocumentViewPicker(); let documentPicker = new picker.DocumentViewPicker();
documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult) => { documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult: Array<string>) => {
console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult));
}).catch((err) => { }).catch((err: BusinessError) => {
console.error('DocumentViewPicker.save failed with err: ' + err); console.error('DocumentViewPicker.save failed with err: ' + err);
}); });
} catch (err) { } catch (err) {
...@@ -418,12 +419,12 @@ save(option: DocumentSaveOptions, callback: AsyncCallback&lt;Array&lt;string&gt; ...@@ -418,12 +419,12 @@ save(option: DocumentSaveOptions, callback: AsyncCallback&lt;Array&lt;string&gt;
**示例:** **示例:**
```ts ```ts
async function example() { async example11() {
try { try {
let DocumentSaveOptions = new picker.DocumentSaveOptions(); let DocumentSaveOptions = new picker.DocumentSaveOptions();
DocumentSaveOptions.newFileNames = ['DocumentViewPicker02.txt']; DocumentSaveOptions.newFileNames = ['DocumentViewPicker02.txt'];
let documentPicker = new picker.DocumentViewPicker(); let documentPicker = new picker.DocumentViewPicker();
documentPicker.save(DocumentSaveOptions, (err, DocumentSaveResult) => { documentPicker.save(DocumentSaveOptions, (err: BusinessError, DocumentSaveResult: Array<string>) => {
if (err) { if (err) {
console.error('DocumentViewPicker.save failed with err: ' + err); console.error('DocumentViewPicker.save failed with err: ' + err);
return; return;
...@@ -453,10 +454,10 @@ save(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void ...@@ -453,10 +454,10 @@ save(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void
**示例:** **示例:**
```ts ```ts
async function example() { async example12() {
try { try {
let documentPicker = new picker.DocumentViewPicker(); let documentPicker = new picker.DocumentViewPicker();
documentPicker.save((err, DocumentSaveResult) => { documentPicker.save((err: BusinessError, DocumentSaveResult: Array<string>) => {
if (err) { if (err) {
console.error('DocumentViewPicker.save failed with err: ' + err); console.error('DocumentViewPicker.save failed with err: ' + err);
return; return;
...@@ -504,13 +505,13 @@ select(option?: AudioSelectOptions) : Promise&lt;Array&lt;string&gt;&gt; ...@@ -504,13 +505,13 @@ select(option?: AudioSelectOptions) : Promise&lt;Array&lt;string&gt;&gt;
**示例:** **示例:**
```ts ```ts
async function example() { async example13() {
try { try {
let AudioSelectOptions = new picker.AudioSelectOptions(); let AudioSelectOptions = new picker.AudioSelectOptions();
let audioPicker = new picker.AudioViewPicker(); let audioPicker = new picker.AudioViewPicker();
audioPicker.select(AudioSelectOptions).then((AudioSelectResult) => { audioPicker.select(AudioSelectOptions).then((AudioSelectResult: Array<string>) => {
console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult));
}).catch((err) => { }).catch((err: BusinessError) => {
console.error('AudioViewPicker.select failed with err: ' + err); console.error('AudioViewPicker.select failed with err: ' + err);
}); });
} catch (err) { } catch (err) {
...@@ -537,11 +538,11 @@ select(option: AudioSelectOptions, callback: AsyncCallback&lt;Array&lt;string&gt ...@@ -537,11 +538,11 @@ select(option: AudioSelectOptions, callback: AsyncCallback&lt;Array&lt;string&gt
**示例:** **示例:**
```ts ```ts
async function example() { async example14() {
try { try {
let AudioSelectOptions = new picker.AudioSelectOptions(); let AudioSelectOptions = new picker.AudioSelectOptions();
let audioPicker = new picker.AudioViewPicker(); let audioPicker = new picker.AudioViewPicker();
audioPicker.select(AudioSelectOptions, (err, AudioSelectResult) => { audioPicker.select(AudioSelectOptions, (err: BusinessError, AudioSelectResult: Array<string>) => {
if (err) { if (err) {
console.error('AudioViewPicker.select failed with err: ' + err); console.error('AudioViewPicker.select failed with err: ' + err);
return; return;
...@@ -571,10 +572,10 @@ select(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void ...@@ -571,10 +572,10 @@ select(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void
**示例:** **示例:**
```ts ```ts
async function example() { async example15() {
try { try {
let audioPicker = new picker.AudioViewPicker(); let audioPicker = new picker.AudioViewPicker();
audioPicker.select((err, AudioSelectResult) => { audioPicker.select((err: BusinessError, AudioSelectResult: Array<string>) => {
if (err) { if (err) {
console.error('AudioViewPicker.select failed with err: ' + err); console.error('AudioViewPicker.select failed with err: ' + err);
return; return;
...@@ -610,14 +611,14 @@ save(option?: AudioSaveOptions) : Promise&lt;Array&lt;string&gt;&gt; ...@@ -610,14 +611,14 @@ save(option?: AudioSaveOptions) : Promise&lt;Array&lt;string&gt;&gt;
**示例:** **示例:**
```ts ```ts
async function example() { async example16() {
try { try {
let AudioSaveOptions = new picker.AudioSaveOptions(); let AudioSaveOptions = new picker.AudioSaveOptions();
AudioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; AudioSaveOptions.newFileNames = ['AudioViewPicker01.mp3'];
let audioPicker = new picker.AudioViewPicker(); let audioPicker = new picker.AudioViewPicker();
audioPicker.save(AudioSaveOptions).then((AudioSaveResult) => { audioPicker.save(AudioSaveOptions).then((AudioSaveResult: Array<string>) => {
console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)) console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult))
}).catch((err) => { }).catch((err: BusinessError) => {
console.error('AudioViewPicker.save failed with err: ' + err); console.error('AudioViewPicker.save failed with err: ' + err);
}); });
} catch (err) { } catch (err) {
...@@ -644,12 +645,12 @@ save(option: AudioSaveOptions, callback: AsyncCallback&lt;Array&lt;string&gt;&gt ...@@ -644,12 +645,12 @@ save(option: AudioSaveOptions, callback: AsyncCallback&lt;Array&lt;string&gt;&gt
**示例:** **示例:**
```ts ```ts
async function example() { async example17() {
try { try {
let AudioSaveOptions = new picker.AudioSaveOptions(); let AudioSaveOptions = new picker.AudioSaveOptions();
AudioSaveOptions.newFileNames = ['AudioViewPicker02.mp3']; AudioSaveOptions.newFileNames = ['AudioViewPicker02.mp3'];
let audioPicker = new picker.AudioViewPicker(); let audioPicker = new picker.AudioViewPicker();
audioPicker.save(AudioSaveOptions, (err, AudioSaveResult) => { audioPicker.save(AudioSaveOptions, (err: BusinessError, AudioSaveResult: Array<string>) => {
if (err) { if (err) {
console.error('AudioViewPicker.save failed with err: ' + err); console.error('AudioViewPicker.save failed with err: ' + err);
return; return;
...@@ -679,10 +680,10 @@ save(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void ...@@ -679,10 +680,10 @@ save(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;) : void
**示例:** **示例:**
```ts ```ts
async function example() { async example18() {
try { try {
let audioPicker = new picker.AudioViewPicker(); let audioPicker = new picker.AudioViewPicker();
audioPicker.save((err, AudioSaveResult) => { audioPicker.save((err: BusinessError, AudioSaveResult: Array<string>) => {
if (err) { if (err) {
console.error('AudioViewPicker.save failed with err: ' + err); console.error('AudioViewPicker.save failed with err: ' + err);
return; return;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册