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