diff --git a/en/application-dev/file-management/app-file-access.md b/en/application-dev/file-management/app-file-access.md index 4d3a21c0902535a3d81fd4be678973b6e8dfab23..92490746d3ca757f76b5892238a4139486cbadb4 100644 --- a/en/application-dev/file-management/app-file-access.md +++ b/en/application-dev/file-management/app-file-access.md @@ -36,7 +36,7 @@ You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement ac First, obtain the [application file path](../application-models/application-context-stage.md#obtaining-application-file-paths). The following example shows how to obtain a HAP file path using **UIAbilityContext**. For details about how to obtain **UIAbilityContext**, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). -Then, perform common file operations. +Then, perform file operations. ### Creating, Reading, and Writing a File @@ -46,21 +46,29 @@ The following example demonstrates how to create a file, read data from it, and // pages/xxx.ets import fs from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; +import buffer from '@ohos.buffer'; -function createFile() { - // Obtain the application file path. - let context = getContext(this) as common.UIAbilityContext; - let filesDir = context.filesDir; +// Obtain the application file path. +let context = getContext(this) as common.UIAbilityContext; +let filesDir = context.filesDir; - // Create a file and open it. +function createFile() { + // Create a file and open it. let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // Write data to the file. let writeLen = fs.writeSync(file.fd, "Try to write str."); console.info("The length of str is: " + writeLen); // Read data from the file. - 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); + class Option { + public offset: number = 0; + public length: number; + } + let option = new Option(); + option.length = arrayBuffer.byteLength; + let readLen = fs.readSync(file.fd, arrayBuffer, option); + let buf = buffer.from(arrayBuffer, 0, readLen); + console.info("the content of file: " + buf.toString()); // Close the file. fs.closeSync(file); } @@ -75,11 +83,11 @@ function createFile() { import fs from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; -function readWriteFile() { - // Obtain the application file path. - let context = getContext(this) as common.UIAbilityContext; - let filesDir = context.filesDir; +// Obtain the application file path. +let context = getContext(this) as common.UIAbilityContext; +let filesDir = context.filesDir; +function readWriteFile() { // Open the source and destination files. let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE); let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); @@ -87,11 +95,18 @@ function readWriteFile() { let bufSize = 4096; let readSize = 0; let buf = new ArrayBuffer(bufSize); - let readLen = fs.readSync(srcFile.fd, buf, { offset: readSize }); + class Option { + public offset: number = 0; + public length: number = bufSize; + } + let option = new Option(); + option.offset = readSize; + let readLen = fs.readSync(srcFile.fd, buf, option); while (readLen > 0) { readSize += readLen; fs.writeSync(destFile.fd, buf); - readLen = fs.readSync(srcFile.fd, buf, { offset: readSize }); + option.offset = readSize; + readLen = fs.readSync(srcFile.fd, buf, option); } // Close the files. fs.closeSync(srcFile); @@ -112,11 +127,11 @@ The following example demonstrates how to read and write file data using a strea import fs from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; -async function readWriteFileWithStream() { - // Obtain the application file path. - let context = getContext(this) as common.UIAbilityContext; - let filesDir = context.filesDir; +// Obtain the application file path. +let context = getContext(this) as common.UIAbilityContext; +let filesDir = context.filesDir; +async function readWriteFileWithStream() { // Open the file streams. let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+'); let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+"); @@ -124,11 +139,18 @@ async function readWriteFileWithStream() { let bufSize = 4096; let readSize = 0; let buf = new ArrayBuffer(bufSize); - let readLen = await inputStream.read(buf, { offset: readSize }); + class Option { + public offset: number = 0; + public length: number = bufSize; + } + let option = new Option(); + option.offset = readSize; + let readLen = await inputStream.read(buf, option); readSize += readLen; while (readLen > 0) { await outputStream.write(buf); - readLen = await inputStream.read(buf, { offset: readSize }); + option.offset = readSize; + readLen = await inputStream.read(buf, option); readSize += readLen; } // Close the streams. @@ -148,8 +170,7 @@ async function readWriteFileWithStream() { The following example demonstrates how to list files that meet the specified conditions. ```ts -// List files. -import fs from '@ohos.file.fs'; +import fs, { Filter } from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; // Obtain the application file path. @@ -157,18 +178,20 @@ let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; // List files that meet the specified conditions. -let options = { - recursion: false, - listNum: 0, - filter: { - suffix: ['.png', '.jpg', '.txt'], // The filename extension can be '.png', '.jpg', or '.txt'. - displayName: ['test%'], // The filename starts with 'test'. - fileSizeOver: 0, // The file size is greater than or equal to 0. - lastModifiedAfter: new Date(0).getTime(), // The latest modification time of the file is later than January 1, 1970. - }, -} -let files = fs.listFileSync(filesDir, options); -for (let i = 0; i < files.length; i++) { - console.info(`The name of file: ${files[i]}`); +function getListFile() { + class ListFileOption { + public recursion: boolean = false; + public listNum: number = 0; + public filter: Filter + } + let option = new ListFileOption(); + option.filter.suffix = ['.png', '.jpg', '.txt']; // The file name extension can be '.png', '.jpg', or '.txt'. + option.filter.displayName = ['test%']; // The file name starts with 'test'. + option.filter.fileSizeOver = 0; // The file size is greater than or equal to 0. + option.filter.lastModifiedAfter = new Date(0).getTime(); // The latest modification time of the file is later than January 1, 1970. + let files = fs.listFileSync(filesDir, option); + for (let i = 0; i < files.length; i++) { + console.info(`The name of file: ${files[i]}`); + } } ``` diff --git a/en/application-dev/file-management/app-file-backup.md b/en/application-dev/file-management/app-file-backup.md index ccfb8641f4db47a71029c2c4591382081aeb0697..e65d2c9e15e12facbbe4ebf56befc29a573d3cb1 100644 --- a/en/application-dev/file-management/app-file-backup.md +++ b/en/application-dev/file-management/app-file-backup.md @@ -32,17 +32,25 @@ The capability file of an application contains the device type, device version, Use **backup.getLocalCapabilities()** to obtain capability files. - ```js + ```ts + import backup from '@ohos.file.backup'; + import common from '@ohos.app.ability.common'; import fs from '@ohos.file.fs'; + + // Obtain the application file path. + let context = getContext(this) as common.UIAbilityContext; + let filesDir = context.filesDir; + async function getLocalCapabilities() { try { let fileData = await backup.getLocalCapabilities(); console.info('getLocalCapabilities success'); - let fpath = await globalThis.context.filesDir + '/localCapabilities.json'; + let fpath = filesDir + '/localCapabilities.json'; fs.copyFileSync(fileData.fd, fpath); fs.closeSync(fileData.fd); - } catch (err) { - console.error('getLocalCapabilities failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err)); } } ``` @@ -88,17 +96,24 @@ You can save the file to a local directory as required. **Example** ```ts + import backup from '@ohos.file.backup'; + import common from '@ohos.app.ability.common'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; + + // Obtain the sandbox path. + let context = getContext(this) as common.UIAbilityContext; + let filesDir = context.filesDir; // Create a SessionBackup instance for data backup. - let g_session; + let g_session: backup.SessionBackup; function createSessionBackup() { - let sessionBackup = new backup.SessionBackup({ - onFileReady: async (err, file) => { + let generalCallbacks: backup.GeneralCallbacks = { + onFileReady: (err: BusinessError, file: backup.File) => { if (err) { - console.info('onFileReady err: ' + err); + console.info('onFileReady err: ' + JSON.stringify(err)); } try { - let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName; + let bundlePath = filesDir + '/' + file.bundleName; if (!fs.accessSync(bundlePath)) { fs.mkdirSync(bundlePath); } @@ -109,23 +124,23 @@ You can save the file to a local directory as required. console.error('onFileReady failed with err: ' + e); } }, - onBundleBegin: (err, bundleName) => { + onBundleBegin: (err: BusinessError, bundleName: string) => { if (err) { - console.info('onBundleBegin err: ' + err); + console.info('onBundleBegin err: ' + JSON.stringify(err)); } else { console.info('onBundleBegin bundleName: ' + bundleName); } }, - onBundleEnd: (err, bundleName) => { + onBundleEnd: (err: BusinessError, bundleName: string) => { if (err) { - console.info('onBundleEnd err: ' + err); + console.info('onBundleEnd err: ' + JSON.stringify(err)); } else { console.info('onBundleEnd bundleName: ' + bundleName); } }, - onAllBundlesEnd: (err) => { + onAllBundlesEnd: (err: BusinessError) => { if (err) { - console.info('onAllBundlesEnd err: ' + err); + console.info('onAllBundlesEnd err: ' + JSON.stringify(err)); } else { console.info('onAllBundlesEnd'); } @@ -133,16 +148,16 @@ You can save the file to a local directory as required. onBackupServiceDied: () => { console.info('onBackupServiceDied'); }, - }); + } + let sessionBackup = new backup.SessionBackup(generalCallbacks); return sessionBackup; } - - async function sessionBackup () - { + + async function sessionBackup () { g_session = createSessionBackup(); // Select the application to be backed up based on the capability file obtained by backup.getLocalCapabilities(). // You can also back up data based on the application bundle name. - const backupApps = [ + const backupApps: string[] = [ "com.example.hiworld", ] await g_session.appendBundles(backupApps); @@ -161,24 +176,26 @@ When all the data of the application is ready, the service starts to restore the **Example** ```ts + import backup from '@ohos.file.backup'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; // Create a SessionRestore instance for data restoration. - let g_session; - async function publishFile(file) - { - await g_session.publishFile({ + let g_session: backup.SessionRestore; + async function publishFile(file: backup.File) { + let fileMeta: backup.FileMeta = { bundleName: file.bundleName, uri: file.uri - }); + } + await g_session.publishFile(fileMeta); } function createSessionRestore() { - let sessionRestore = new backup.SessionRestore({ - onFileReady: (err, file) => { + let generalCallbacks: backup.GeneralCallbacks = { + onFileReady: (err: BusinessError, file: backup.File) => { if (err) { - console.info('onFileReady err: ' + err); + console.info('onFileReady err: ' + JSON.stringify(err)); } // Set bundlePath based on the actual situation. - let bundlePath; + let bundlePath: string; if (!fs.accessSync(bundlePath)) { console.info('onFileReady bundlePath err : ' + bundlePath); } @@ -188,52 +205,51 @@ When all the data of the application is ready, the service starts to restore the publishFile(file); console.info('onFileReady success'); }, - onBundleBegin: (err, bundleName) => { + onBundleBegin: (err: BusinessError, bundleName: string) => { if (err) { - console.error('onBundleBegin failed with err: ' + err); + console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); } console.info('onBundleBegin success'); }, - onBundleEnd: (err, bundleName) => { + onBundleEnd: (err: BusinessError, bundleName: string) => { if (err) { - console.error('onBundleEnd failed with err: ' + err); + console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); } console.info('onBundleEnd success'); }, - onAllBundlesEnd: (err) => { + onAllBundlesEnd: (err: BusinessError) => { if (err) { - console.error('onAllBundlesEnd failed with err: ' + err); + console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); } console.info('onAllBundlesEnd success'); }, onBackupServiceDied: () => { console.info('service died'); } - }); + } + let sessionRestore = new backup.SessionRestore(generalCallbacks); return sessionRestore; } - - async function restore () - { + + async function restore01 () { g_session = createSessionRestore(); - const backupApps = [ + const restoreApps: string[] = [ "com.example.hiworld", ] // You can obtain the capability file based on actual situation. The following is an example only. // You can also construct capability files as required. let fileData = await backup.getLocalCapabilities(); - await g_session.appendBundles(fileData.fd, backupApps); + await g_session.appendBundles(fileData.fd, restoreApps); console.info('appendBundles success'); // After the applications to be restored are added, call getFileHandle() to obtain the handles of the application files to be restored based on the application name. // The number of application data files to be restored varies depending on the number of backup files. The following is only an example. - await g_session.getFileHandle({ + let handle: backup.FileMeta = { bundleName: restoreApps[0], uri: "manage.json" - }); - await g_session.getFileHandle({ - bundleName: restoreApps[0], - uri: "1.tar" - }); + } + await g_session.getFileHandle(handle); + handle.uri = "1.tar"; + await g_session.getFileHandle(handle); console.info('getFileHandle success'); } ``` @@ -249,23 +265,30 @@ If the application has not been installed, you can install the application and t **Example** ```ts + import backup from '@ohos.file.backup'; + import common from '@ohos.app.ability.common'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; + + // Obtain the sandbox path. + let context = getContext(this) as common.UIAbilityContext; + let filesDir = context.filesDir; // Create a SessionRestore instance for data restoration. - let g_session; - async function publishFile(file) - { - await g_session.publishFile({ + let g_session: backup.SessionRestore; + async function publishFile(file: backup.File) { + let fileMeta: backup.FileMeta = { bundleName: file.bundleName, uri: file.uri - }); + } + await g_session.publishFile(fileMeta); } function createSessionRestore() { - let sessionRestore = new backup.SessionRestore({ - onFileReady: (err, file) => { - if (err) { - console.info('onFileReady err: ' + err); - } - let bundlePath; + let generalCallbacks: backup.GeneralCallbacks = { + onFileReady: (err: BusinessError, file: backup.File) => { + if (err) { + console.info('onFileReady err: ' + JSON.stringify(err)); + } + let bundlePath: string; if( file.uri == "/data/storage/el2/restore/bundle.hap" ) { // Set the path of the application installation package based on actual situation. @@ -281,61 +304,57 @@ If the application has not been installed, you can install the application and t publishFile(file); console.info('onFileReady success'); }, - onBundleBegin: (err, bundleName) => { + onBundleBegin: (err: BusinessError, bundleName: string) => { if (err) { - console.error('onBundleBegin failed with err: ' + err); + console.error('onBundleBegin failed with err: ' + JSON.stringify(err)); } console.info('onBundleBegin success'); }, - onBundleEnd: (err, bundleName) => { + onBundleEnd: (err: BusinessError, bundleName: string) => { if (err) { - console.error('onBundleEnd failed with err: ' + err); + console.error('onBundleEnd failed with err: ' + JSON.stringify(err)); } console.info('onBundleEnd success'); }, - onAllBundlesEnd: (err) => { + onAllBundlesEnd: (err: BusinessError) => { if (err) { - console.error('onAllBundlesEnd failed with err: ' + err); + console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err)); } console.info('onAllBundlesEnd success'); }, onBackupServiceDied: () => { console.info('service died'); } - }); + } + let sessionRestore = new backup.SessionRestore(generalCallbacks); return sessionRestore; } - - async function restore () - { + + async function restore02 () { g_session = createSessionRestore(); - const backupApps = [ + const restoreApps: string[] = [ "com.example.hiworld", ] - let fpath = await globalThis.context.filesDir + '/localCapabilities.json'; - let file = fs.openSync(fpath, fileIO.OpenMode.CREATE | fileIO.OpenMode.READ_WRITE); + let fpath = filesDir + '/localCapabilities.json'; + let file = fs.openSync(fpath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); let content = "{\"bundleInfos\" :[{\"allToBackup\" : false,\"extensionName\" : \"\"," + "\"name\" : \"cn.openharmony.inputmethodchoosedialog\",\"needToInstall\" : true,\"spaceOccupied\" : 0," + "\"versionCode\" : 1000000,\"versionName\" : \"1.0.0\"}],\"deviceType\" : \"default\",\"systemFullName\" : \"OpenHarmony-4.0.6.2(Canary1)\"}"; fs.writeSync(file.fd, content); fs.fsyncSync(file.fd); - await g_session.appendBundles(file.fd, backupApps); + await g_session.appendBundles(file.fd, restoreApps); console.info('appendBundles success'); - + // Obtain the file handle of the application to be installed. - await g_session.getFileHandle({ + let handle: backup.FileMeta = { bundleName: restoreApps[0], uri: "/data/storage/el2/restore/bundle.hap" - }); - - await g_session.getFileHandle({ - bundleName: restoreApps[0], - uri: "manage.json" - }); - await g_session.getFileHandle({ - bundleName: restoreApps[0], - uri: "1.tar" - }); + } + await g_session.getFileHandle(handle); + handle.uri = "manage.json"; + await g_session.getFileHandle(handle); + handle.uri = "1.tar"; + await g_session.getFileHandle(handle); console.info('getFileHandle success'); } ``` diff --git a/en/application-dev/file-management/app-file-upload-download.md b/en/application-dev/file-management/app-file-upload-download.md index 75fb0646cf2dbfa1422209c4d4b9b176e547f749..d2391e620a8327964010703ad523a30f732aaa10 100644 --- a/en/application-dev/file-management/app-file-upload-download.md +++ b/en/application-dev/file-management/app-file-upload-download.md @@ -19,6 +19,7 @@ The following example demonstrates how to upload a file in the **cache** directo import common from '@ohos.app.ability.common'; import fs from '@ohos.file.fs'; import request from '@ohos.request'; +import { BusinessError } from '@ohos.base'; // Obtain the application file path. let context = getContext(this) as common.UIAbilityContext; @@ -30,32 +31,36 @@ fs.writeSync(file.fd, 'upload file test'); fs.closeSync(file); // Configure the upload task. -let uploadConfig = { +let header = new Map(); +header.set('key1', 'value1'); +header.set('key2', 'value2'); +let files: Array = [ + { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } +] +let data: Array = [{ name: 'name', value: 'value' }]; +let uploadConfig: request.UploadConfig = { url: 'https://xxx', - header: { key1: 'value1', key2: 'value2' }, + header: header, method: 'POST', - files: [ - { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } - ], - data: [ - { name: 'name', value: 'value' } - ] + files: files, + data: data } // Upload the created application file to the network server. try { request.uploadFile(context, uploadConfig) - .then((uploadTask) => { - uploadTask.on('complete', (taskStates) => { + .then((uploadTask: request.UploadTask) => { + uploadTask.on('complete', (taskStates: Array) => { 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) { +} catch (error) { + let err: BusinessError = error as BusinessError; console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -78,6 +83,8 @@ The following example demonstrates how to download a network resource file to a import common from '@ohos.app.ability.common'; import fs from '@ohos.file.fs'; import request from '@ohos.request'; +import { BusinessError } from '@ohos.base'; +import buffer from '@ohos.buffer'; // Obtain the application file path. let context = getContext(this) as common.UIAbilityContext; @@ -87,19 +94,21 @@ 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) { +} catch (error) { + let err: BusinessError = error as BusinessError; console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`); } ``` diff --git a/en/application-dev/file-management/app-fs-space-statistics.md b/en/application-dev/file-management/app-fs-space-statistics.md index 74ffbc6c6f39441be0a9c0043389458025bc0c0d..ebc0982502719a6d07e98ed5f46329744dfcf55d 100644 --- a/en/application-dev/file-management/app-fs-space-statistics.md +++ b/en/application-dev/file-management/app-fs-space-statistics.md @@ -10,13 +10,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi | Module| API| Description| | -------- | -------- | -------- | -| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.| -| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.| -| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.| +| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.| +| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.| +| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.| **Table 2** Attributes for application space statistics -| BundleStats Attribute| Description| Directory for Statistics| +| BundleStats Attribute| Description| Directory for Statistics| | -------- | -------- | -------- | | appSize | Size of the application installation files, in bytes.| /data/storage/el1/bundle | | cacheSize | Size of the application cache files, in bytes.| /data/storage/el1/base/cache
/data/storage/el1/base/haps/entry/cache
/data/storage/el2/base/cache
/data/storage/el2/base/haps/entry/cache | @@ -25,12 +25,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi ## Development Example - Obtain the free space of **/data** of the file system. - + ```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 { @@ -40,11 +41,12 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi ``` - Obtain the space occupied by the current application. - + ```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 { diff --git a/en/application-dev/file-management/dev-user-file-manager.md b/en/application-dev/file-management/dev-user-file-manager.md index ffcea027cfc56ad761064bd686f06452bc6be390..4340e26a14d41dab029f75b45dd259015ee67e7d 100644 --- a/en/application-dev/file-management/dev-user-file-manager.md +++ b/en/application-dev/file-management/dev-user-file-manager.md @@ -8,82 +8,89 @@ For details about the APIs used to develop a file manager application, see [User ## How to Develop -1. Apply for permissions required.
- Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md). +1. Apply for permissions required. + Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md). > **NOTE** > - > **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs. - > - > **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system. - + > - **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs. + >- **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system. 2. Import dependent modules. ```ts import fileAccess from '@ohos.file.fileAccess'; import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; + import { Filter } from '@ohos.file.fs'; + import common from '@ohos.app.ability.common'; + import { BusinessError } from '@ohos.base'; ``` The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development. -3. Query device information.
+3. Query device information. + You can obtain attributes of the devices managed by one or all file management servers in the system. You can also filter devices as required. In the user file access framework, **RootInfo** indicates the attribute information of a device. For example, obtain **RootInfo** of all devices. ```ts + // Obtain the application context. + let context = getContext(this) as common.UIAbilityContext; + // Create a helper object for connecting to all file management servers in the system. - let fileAccessHelperAllServer = null; - createFileAccessHelper() { + let fileAccessHelperAllServer: fileAccess.FileAccessHelper; + function createFileAccessHelper() { try { // this.context is the context passed from EntryAbility. - fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context); + fileAccessHelperAllServer = fileAccess.createFileAccessHelper(context); if (!fileAccessHelperAllServer) { console.error("createFileAccessHelper interface returns an undefined object"); } - } catch (error) { + } catch (err) { + let error: BusinessError = err as BusinessError; console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); } } - async getRoots() { - let rootIterator = null; - let rootInfos = []; - let isDone = false; + let rootInfos: Array = []; + async function getRoots() { + let rootIterator: fileAccess.RootIterator; + 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); - } - } catch (error) { + rootInfos.push(result.value); + } + } catch (err) { + let error: BusinessError = err as BusinessError; console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message); } } ``` 4. View directories. + In the user file access framework, **FileInfo** indicates basic information about a file (directory). You can use **listfile()** to obtain a **FileIterator** object that traverses all files (directories) of the next level or use **scanfile()** to obtain a **FileIterator** object that meets the specified conditions. Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse the next-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse the next-level files or filter the specified directories. ```ts // Start from the root directory. - let rootInfo = rootinfos[0]; - let fileInfos = []; - let isDone = false; - let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria. - try { - let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object. - // let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object. + let rootInfo = rootInfos[0]; + let fileInfos: Array = []; + let isDone: boolean = false; + let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter. + try { + let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object. + // let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object. if (!fileIterator) { console.error("listFile interface returns an undefined object"); - return; } while (!isDone) { let result = fileIterator.next(); @@ -92,35 +99,37 @@ For details about the APIs used to develop a file manager application, see [User if (!isDone) fileInfos.push(result.value); } - } catch (error) { + } catch (err) { + let error: BusinessError = err as BusinessError; console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message); } - + // Start from the specified directory. - let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory. - let subFileInfos = []; - let isDone = false; - let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria. + let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory. + let subFileInfos: Array = []; + let isDone02: boolean = false; + let filter02: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter. try { - let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object. - // let fileIterator = rootInfo.scanFile(filter); // Filter the files in the specified directory and return an iterator object. + let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object. + // let fileIterator = rootInfo.scanFile(filter02); // Filter the files in the specified directory and return an iterator object. if (!fileIterator) { console.error("listFile interface returns an undefined object"); - return; } - while (!isDone) { + while (!isDone02) { let result = fileIterator.next(); console.info("next result = " + JSON.stringify(result)); - isDone = result.done; - if (!isDone) - subfileInfos.push(result.value); + isDone02 = result.done; + if (!isDone02) + subFileInfos.push(result.value); } - } catch (error) { + } catch (err) { + let error: BusinessError = err as BusinessError; console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message); } ``` 5. Perform operations on files or directories. + You can integrate APIs of the user file access framework to implement user behaviors, such as deleting, renaming, creating, and moving a file (directory). The following example shows how to create a file. For details about other APIs, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md). ```ts @@ -128,18 +137,20 @@ For details about the APIs used to develop a file manager application, see [User // Create a file. // sourceUri is the URI in fileinfo of the Download directory. // You need to use the obtained URI for development. - let sourceUri = "file://media/file/6"; - let displayName = "file1"; - let fileUri = null; - try { - // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. - fileUri = await fileAccessHelper.createFile(sourceUri, displayName); - if (!fileUri) { - console.error("createFile return undefined object"); - return; - } - console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri)); - } catch (error) { - console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); - }; + async function creatFile() { + let sourceUri: string = "file://docs/storage/Users/currentUser/Download"; + let displayName: string = "file1"; + let fileUri: string; + try { + // Obtain fileAccessHelperAllServer by referring to the sample code of fileAccess.createFileAccessHelper. + fileUri = await fileAccessHelperAllServer.createFile(sourceUri, displayName); + if (!fileUri) { + console.error("createFile return undefined object"); + } + console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri)); + } catch (err) { + let error: BusinessError = err as BusinessError; + console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + } ``` diff --git a/en/application-dev/file-management/file-access-across-devices.md b/en/application-dev/file-management/file-access-across-devices.md index 1fefd8c41154597235e718b77309f34c94a36778..caa18468fb0eccd535ebe095ab9c45ab3f7549fb 100644 --- a/en/application-dev/file-management/file-access-across-devices.md +++ b/en/application-dev/file-management/file-access-across-devices.md @@ -8,8 +8,7 @@ For example, device A and device B are installed with the same application. Afte 1. Connect the devices to form a Super Device. -Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number. - + Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number. 2. Implement cross-device access to the files of the same application. Place the files in the **distributedfiles/** directory of the application sandbox to implement access from difference devices. @@ -18,11 +17,13 @@ Connect the devices to a LAN, and complete authentication of the devices. The de ```ts import fs from '@ohos.file.fs'; - - let context =...; // Obtain the UIAbilityContext information of device A. - let pathDir = context.distributedFilesDir; + import common from '@ohos.app.ability.common'; + import { BusinessError } from '@ohos.base'; + + let context = getContext(this) as common.UIAbilityContext; // Obtain the UIAbilityContext of device A. + let pathDir: string = context.distributedFilesDir; // Obtain the file path of the distributed directory. - let filePath = pathDir + '/test.txt'; + let filePath: string = pathDir + '/test.txt'; try { // Create a file in the distributed directory. @@ -32,7 +33,8 @@ Connect the devices to a LAN, and complete authentication of the devices. The de fs.writeSync(file.fd, 'content'); // Close the file. fs.closeSync(file.fd); - } catch (err) { + } catch (error) { + let err: BusinessError = error as BusinessError; console.error(`Failed to openSync / writeSync / closeSync. Code: ${err.code}, message: ${err.message}`); } ``` @@ -41,24 +43,33 @@ Connect the devices to a LAN, and complete authentication of the devices. The de ```ts import fs from '@ohos.file.fs'; + import common from '@ohos.app.ability.common'; + import buffer from '@ohos.buffer'; + import { BusinessError } from '@ohos.base'; - let context =...; // Obtain the UIAbilityContext information of device B. - let pathDir = context.distributedFilesDir; + let context = getContext(this) as common.UIAbilityContext; // Obtain the UIAbilityContext of device B. + let pathDir: string = context.distributedFilesDir; // Obtain the file path of the distributed directory. - let filePath = pathDir + '/test.txt'; + let filePath: string = pathDir + '/test.txt'; try { // Open the file in the distributed directory. let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); // Set the buffer for receiving the read data. - let buffer = new ArrayBuffer(4096); + let arrayBuffer = new ArrayBuffer(4096); // Read the file. The return value is the number of read bytes. - let num = fs.readSync(file.fd, buffer, { - offset: 0 - }); + class Option { + public offset: number = 0; + public length: number; + } + let option = new Option(); + option.length = arrayBuffer.byteLength; + let num = fs.readSync(file.fd, arrayBuffer, option); // Print the read data. - console.info('read result: ' + String.fromCharCode.apply(null, new Uint8Array(buffer.slice(0, num)))); - } catch (err) { + let buf = buffer.from(arrayBuffer, 0, num); + console.info('read result: ' + buf.toString()); + } catch (error) { + let err: BusinessError = error as BusinessError; console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`); } ``` diff --git a/en/application-dev/file-management/manage-external-storage.md b/en/application-dev/file-management/manage-external-storage.md index b26a17455725e769f41cf1eb2cdc6d214ee3a0e9..24a0a3b112845e47ce2b8e0a9e32d2b53b4b1e3d 100644 --- a/en/application-dev/file-management/manage-external-storage.md +++ b/en/application-dev/file-management/manage-external-storage.md @@ -28,13 +28,13 @@ The following table describes the broadcast related parameters. **Table 1** Broadcast parameters -| Broadcast| Parameter| +| Broadcast| Parameter| | -------- | -------- | -| usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| -| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| -| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.
**fsUuid**: universally unique identifier (UUID) of the volume.
**path**: path where the volume is mounted.| -| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| -| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| +| usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| +| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| +| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.
**fsUuid**: universally unique identifier (UUID) of the volume.
**path**: path where the volume is mounted.| +| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| +| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| ## How to Develop @@ -55,29 +55,33 @@ You can subscribe to broadcast events to observe the insertion and removal of ex ```ts import CommonEvent from '@ohos.commonEventManager'; import volumeManager from '@ohos.file.volumeManager'; - - const subscribeInfo = { + import { BusinessError } from '@ohos.base'; + + let subscriber: CommonEvent.CommonEventSubscriber; + async function example() { + const subscribeInfo: CommonEvent.CommonEventSubscribeInfo = { events: [ - "usual.event.data.VOLUME_REMOVED", - "usual.event.data.VOLUME_UNMOUNTED", - "usual.event.data.VOLUME_MOUNTED", - "usual.event.data.VOLUME_BAD_REMOVAL", - "usual.event.data.VOLUME_EJECT" - ] - }; - let subscriber = await CommonEvent.createSubscriber(subscribeInfo); + "usual.event.data.VOLUME_REMOVED", + "usual.event.data.VOLUME_UNMOUNTED", + "usual.event.data.VOLUME_MOUNTED", + "usual.event.data.VOLUME_BAD_REMOVAL", + "usual.event.data.VOLUME_EJECT" + ] + }; + subscriber = await CommonEvent.createSubscriber(subscribeInfo); + } ``` 3. Obtain volume information from the broadcast. ```ts - CommonEvent.subscribe(subscriber, function (err, data) { + CommonEvent.subscribe(subscriber, (err: BusinessError, data: CommonEvent.CommonEventData) => { if (data.event === 'usual.event.data.VOLUME_MOUNTED') { // Manage the volume device based on the information obtained from the broadcast. - 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'); + console.error('volumeManager getVolumeById failed for ' + JSON.stringify(error)); } else { console.info('volumeManager getVolumeById successfully, the volume state is ' + vol.state); } diff --git a/en/application-dev/file-management/save-user-file.md b/en/application-dev/file-management/save-user-file.md index c07a6d898927f57506ca789f131aa8ac70d3cf20..07ef6bc424991b79b8305cd3795534317d00845c 100644 --- a/en/application-dev/file-management/save-user-file.md +++ b/en/application-dev/file-management/save-user-file.md @@ -11,44 +11,48 @@ The **save()** method saves files in the file manager, not in **Gallery**. For example, select an image from **Gallery** and save it to the file manager. -1. Import the [picker](../reference/apis/js-apis-file-picker.md), [fs](../reference/apis/js-apis-file-fs.md), [photoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md), and [dataSharePredicates] (../reference/apis/js-apis-data-dataSharePredicates.md) modules. +1. Import the [picker](../reference/apis/js-apis-file-picker.md), [fs](../reference/apis/js-apis-file-fs.md), [photoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md), and [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) modules. ```ts import picker from '@ohos.file.picker'; 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. Obtain the thumbnail of the first image on the device. Before performing this operation, ensure that at least one image exists on the device. ```ts - const context = getContext(this); - let photoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); + let context = getContext(this) as common.UIAbilityContext; + let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); - let pixelmapArrayBuffer; - async getPixelmap() { + let pixelmapArrayBuffer: ArrayBuffer; + async function 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) => { - console.error('[picker] getThumbnail failed with error: ' + err); + }).catch((err: BusinessError) => { + console.error('[picker] getThumbnail failed with error: ' + JSON.stringify(err)); }); } catch (error) { - console.error('[picker] getThumbnail error = ' + error); + let err: BusinessError = error as BusinessError; + console.error('[picker] getThumbnail error = ' + JSON.stringify(err)); } } ``` @@ -58,8 +62,8 @@ For example, select an image from **Gallery** and save it to the file manager. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let uri:string; - async photoViewPickerSave() { + let uris: Array; + async function photoViewPickerSave() { try { const photoSaveOptions = new picker.PhotoSaveOptions(); // Create a photoSaveOptions instance. photoSaveOptions.newFileNames = ["PhotoViewPicker01.png"]; // (Optional) Name of the file to be saved. The file name in the square brackets can be customized and must be unique. If the file name already exists on the device, change the file name. Otherwise, an error will be returned. @@ -68,15 +72,16 @@ For example, select an image from **Gallery** and save it to the file manager. try { let photoSaveResult = await photoViewPicker.save(photoSaveOptions); if (photoSaveResult != undefined) { - console.info("[picker] photoViewPickerSave photoSaveResult = " + JSON.stringify(photoSaveResult)); - this.uri = photoSaveResult[0]; - console.info('photoViewPicker.save to file succeed and uri is:' + photoSaveResult[0]); + uris = photoSaveResult; + console.info('photoViewPicker.save to file succeed and uris are:' + uris); } - } catch (err) { + } catch (error) { + let err: BusinessError = error as BusinessError; console.error(`[picker] Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`); } } catch (error) { - console.info("[picker] photoViewPickerSave error = " + error); + let err: BusinessError = error as BusinessError; + console.info("[picker] photoViewPickerSave error = " + JSON.stringify(err)); } } ``` @@ -86,14 +91,15 @@ For example, select an image from **Gallery** and save it to the file manager. Then, use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to modify the file based on the FD, and close the FD after the modification is complete. ```ts - async writeOnly(uri) { + async function writeOnly(uri: string) { try { let file = fs.openSync(uri, fs.OpenMode.WRITE_ONLY); let writeLen = await fs.write(file.fd, pixelmapArrayBuffer); fs.closeSync(file); console.info("[picker] writeOnly writeLen = " + writeLen); } catch (error) { - console.info("[picker] writeOnly error: " + error); + let err: BusinessError = error as BusinessError; + console.info("[picker] writeOnly error: " + JSON.stringify(err)); } } ``` @@ -105,6 +111,7 @@ For example, select an image from **Gallery** and save it to the file manager. ```ts import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; ``` 2. Create a **documentSaveOptions** instance. @@ -112,6 +119,7 @@ For example, select an image from **Gallery** and save it to the file manager. ```ts const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance. documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the name of the document to save. + documentSaveOptions.fileSuffixChoices = ['.png', '.txt', '.mp4']; // (Optional) Types of the documents to save. ``` 3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the document. After the user selects the destination folder, the document is saved and the URI of the document saved is returned. @@ -119,12 +127,12 @@ For example, select an image from **Gallery** and save it to the file manager. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let uri = null; + let uris: Array; const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance. - documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => { - uri = documentSaveResult[0]; - console.info('documentViewPicker.save to file succeed and uri is:' + uri); - }).catch((err) => { + documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array) => { + uris = documentSaveResult; + console.info('documentViewPicker.save to file succeed and uris are:' + uris); + }).catch((err: BusinessError) => { console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -151,6 +159,7 @@ For example, select an image from **Gallery** and save it to the file manager. ```ts import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; ``` 2. Create an **audioSaveOptions** instance. @@ -160,17 +169,17 @@ For example, select an image from **Gallery** and save it to the file manager. audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the name of the audio file to save. ``` -3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the file. After the user selects the destination folder, the audio file is saved and the URI of the file saved is returned. +3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the file. After the user selects the destination folder, the audio file is saved and the URI of the document saved is returned. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let uri = null; + let uri: string; const audioViewPicker = new picker.AudioViewPicker(); - audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => { + audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array) => { 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}`); }) ``` @@ -182,7 +191,7 @@ For example, select an image from **Gallery** and save it to the file manager. console.info('file fd: ' + file.fd); ``` -5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD. +5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the document based on the FD, and then close the FD. ```ts let writeLen = fs.writeSync(file.fd, 'hello, world'); diff --git a/en/application-dev/file-management/select-user-file.md b/en/application-dev/file-management/select-user-file.md index 041d20f308e47b7757de53a4735958e54bba6f2e..01f074fff61c84ebd1e04885e895a261599d1de7 100644 --- a/en/application-dev/file-management/select-user-file.md +++ b/en/application-dev/file-management/select-user-file.md @@ -17,6 +17,7 @@ The **FilePicker** provides the following interfaces by file type: ```ts import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; ``` 2. Create a **photoSelectOptions** instance. @@ -38,12 +39,12 @@ The **FilePicker** provides the following interfaces by file type: The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. ```ts - let uri = null; + let uris: Array; const photoViewPicker = new picker.PhotoViewPicker(); - photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => { - uri = photoSelectResult.photoUris[0]; - console.info('photoViewPicker.select to file succeed and uri is:' + uri); - }).catch((err) => { + photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => { + uris = photoSelectResult.photoUris; + console.info('photoViewPicker.select to file succeed and uris are:' + uris); + }).catch((err: BusinessError) => { console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -71,12 +72,17 @@ The **FilePicker** provides the following interfaces by file type: ```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. Create a **documentSelectOptions** instance. ```ts const documentSelectOptions = new picker.DocumentSelectOptions(); + documentSelectOptions.maxSelectNumber = 5; // (Optional) Maximum number of documents to select. + documentSelectOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test"; // (Optional) Path of the file or directory to select. + documentSelectOptions.fileSuffixFilters = ['.png', '.txt', '.mp4']; // (Optional) File name extensions of the documents to select. ``` 3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents. After the documents are selected, a result set containing the file URIs is returned. @@ -85,17 +91,13 @@ The **FilePicker** provides the following interfaces by file type: For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attributes, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md). - > **NOTE** - > - > Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected. - ```ts - let uri = null; + let uris: Array; const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance. - documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { - uri = documentSelectResult[0]; - console.info('documentViewPicker.select to file succeed and uri is:' + uri); - }).catch((err) => { + documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array) => { + uris = documentSelectResult; + console.info('documentViewPicker.select to file succeed and uris are:' + uris); + }).catch((err: BusinessError) => { console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -105,24 +107,27 @@ The **FilePicker** provides the following interfaces by file type: > Currently, **DocumentSelectOptions** cannot be used to obtain the file name. To obtain the file name, use **startAbilityForResult()**. ```ts - let config = { - action: 'ohos.want.action.OPEN_FILE', - parameters: { - startMode: 'choose', + async function example() { + let config: Want = { + action: 'ohos.want.action.OPEN_FILE', + parameters: { + startMode: 'choose', + } } - } - try { - let result = await context.startAbilityForResult(config, {windowMode: 1}); - if (result.resultCode !== 0) { - console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`); - return; + try { + let result = await context.startAbilityForResult(config, {windowMode: 1}); + if (result.resultCode !== 0) { + console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`); + return; + } + // Obtain the URI of the document. + let select_item_list = result.want.parameters.select_item_list; + // Obtain the name of the document. + let file_name_list = result.want.parameters.file_name_list; + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); } - // Obtain the URI of the document. - let select_item_list = result.want.parameters.select_item_list; - // Obtain the name of the document. - let file_name_list = result.want.parameters.file_name_list; - } catch (err) { - console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -150,6 +155,7 @@ The **FilePicker** provides the following interfaces by file type: ```ts import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; ``` 2. Create an **audioSelectOptions** instance. @@ -169,12 +175,12 @@ The **FilePicker** provides the following interfaces by file type: > Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected. ```ts - let uri = null; + let uri: string; const audioViewPicker = new picker.AudioViewPicker(); - audioViewPicker.select(audioSelectOptions).then(audioSelectResult => { - uri = audioSelectOptions[0]; + audioViewPicker.select(audioSelectOptions).then((audioSelectResult: Array) => { + 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}`); }) ``` diff --git a/en/application-dev/file-management/set-security-label.md b/en/application-dev/file-management/set-security-label.md index 2bf82ab58daa28d82b3c9a7ec2c38162a6ad210c..cb8e133b76f0d5caa0648bd585cd383705f45267 100644 --- a/en/application-dev/file-management/set-security-label.md +++ b/en/application-dev/file-management/set-security-label.md @@ -13,7 +13,7 @@ For details about the APIs, see [ohos.file.securityLabel](../reference/apis/js-a | setSecurityLabel | Sets a security label for a file.| Method| √ | √ | | getSecurityLabel | Obtains the security label of a file.| Method| √ | √ | -> **NOTE** +> **NOTICE** > > - In distributed networking, a device can view the files that do not match its security level but cannot access them. > @@ -26,16 +26,18 @@ Obtain the sandbox path of a file and set the data security label. For details a ```ts import securityLabel from '@ohos.file.securityLabel'; +import { BusinessError } from '@ohos.base'; +import common from '@ohos.app.ability.common'; // Obtain the sandbox path of the file. -let context =...; // Obtain UIAbilityContext information. +let context = getContext(this) as common.UIAbilityContext; // Obtain UIAbilityContext. let pathDir = context.filesDir; let filePath = pathDir + '/test.txt'; // Set the data level of the file to 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}`); }); ``` diff --git a/en/application-dev/file-management/share-app-file.md b/en/application-dev/file-management/share-app-file.md index 76dbcab2a74b6b6a4afdcee72c4535939cf3e0a0..f912565dbd58062f95c88cc35f45c60807a290aa 100644 --- a/en/application-dev/file-management/share-app-file.md +++ b/en/application-dev/file-management/share-app-file.md @@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing The file URIs are in the following format: - **file**://<*bundleName*>/<*path*> +**file://**<bundleName>/<path> - **file**: indicates a file URI. @@ -30,7 +30,7 @@ Before sharing application files, you need to [obtain the application file path] import UIAbility from '@ohos.app.ability.UIAbility'; import fileuri from '@ohos.file.fileuri'; import window from '@ohos.window'; - + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { // Obtain the application sandbox path of the file. @@ -43,6 +43,7 @@ Before sharing application files, you need to [obtain the application file path] ``` 2. Set the target application, with which you want to share the file, and grant permissions on the file. + Use [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to share the file with the target application. You need to pass in the obtained URI in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis/js-apis-app-ability-want.md#attributes). > **NOTE** @@ -51,37 +52,39 @@ Before sharing application files, you need to [obtain the application file path] ```ts import fileuri from '@ohos.file.fileuri'; - import window from '@ohos.window'; - import wantConstant from '@ohos.app.ability.wantConstant'; - import UIAbility from '@ohos.app.ability.UIAbility'; - - export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { - // Obtain the application sandbox path of the file. - let filePath = this.context.filesDir + '/test.txt'; - // Convert the application sandbox path into a URI. - let uri = fileuri.getUriFromPath(filePath); - let want = { - // Grant the read and write permissions on the shared file to the target application. - flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - // Set the implicit startup rule for the application that shares the file. - action: 'ohos.want.action.sendData', - uri: uri, - type: 'text/plain' - } - this.context.startAbility(want) - .then(() => { - console.info('Invoke getCurrentBundleStats succeeded.'); - }) - .catch((err) => { - console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`); - }); - } - - ... - } + 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) { + // Obtain the application sandbox path of the file. + let filePath = this.context.filesDir + '/test.txt'; + // Convert the application sandbox path into a URI. + let uri = fileuri.getUriFromPath(filePath); + let want: Want = { + // Grant the read and write permissions on the shared file to the target application. + flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, + // Set the implicit startup rule for the application that shares the file. + action: 'ohos.want.action.sendData', + uri: uri, + type: 'text/plain' + } + this.context.startAbility(want) + .then(() => { + console.info('Invoke getCurrentBundleStats succeeded.'); + }) + .catch((err: BusinessError) => { + console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`); + }); + } + // ... + } ``` + ## Using Shared Files In the [**module.json5** file](../quick-start/module-configuration-file.md) of the application, which wants to use the shared file, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by another application and set **uris** to the type of the URI to receive. In the following example, the application receives only .txt files with **scheme** of **file**. @@ -120,10 +123,12 @@ After obtaining the URI of the shared file from **want**, the application can ca ```ts // xxx.ets import fs from '@ohos.file.fs'; +import Want from '@ohos.app.ability.Want'; +import { BusinessError } from '@ohos.base'; function getShareFile() { try { - let want =...; // Obtain the want information sent from the application that shares the file. + let want: Want = ...; // Obtain the want sent from the application that shares the file. // Obtain the uri field from the want information. let uri = want.uri; @@ -135,11 +140,13 @@ function getShareFile() { // Perform operations on the URI of the shared file as required. For example, open the URI to obtain the file object in read/write mode. let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); console.info('open file successfully!'); - } catch (error) { + } catch (err) { + let error: BusinessError = err as BusinessError; console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`); } } catch (error) { - console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`); + let err: BusinessError = error as BusinessError; + console.error(`Invoke openSync failed, code is ${err.code}, message is ${err.message}`); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-file-picker.md b/en/application-dev/reference/apis/js-apis-file-picker.md index b8572f3bf4df0d6a60b5f7835ac1bf9346d19b1f..67359466507eb63ec3042ce8829d11458264c770 100644 --- a/en/application-dev/reference/apis/js-apis-file-picker.md +++ b/en/application-dev/reference/apis/js-apis-file-picker.md @@ -8,8 +8,13 @@ ## Modules to Import -```js +> **NOTE** +> +> You need to import the **BusinessError** module if **BusinessError** is used in the sample code. + +```ts import picker from '@ohos.file.picker'; +import { BusinessError } from '@ohos.base'; ``` ## PhotoViewPicker @@ -47,19 +52,20 @@ Selects one or more images or videos in a **photoPicker** page. This API uses a **Example** ```ts -async function example() { +async function 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) => { - console.error('PhotoViewPicker.select failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -82,21 +88,22 @@ Selects one or more images or videos in a **photoPicker** page. This API uses an **Example** ```ts -async function example() { - try { +async function 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); + console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -118,18 +125,19 @@ Selects one or more images or videos in a **photoPicker** page. This API uses an **Example** ```ts -async function example() { - try { +async function 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); + console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -138,7 +146,7 @@ async function example() { save(option?: PhotoSaveOptions) : Promise<Array<string>> -Saves one or more images or videos in a **photoPicker** page. This API uses a promise to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves the file in the file manager, not in the Gallery. +Saves one or more images or videos in a **photoPicker** page. This API uses a promise to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves files in the file manager, not in **Gallery**. **System capability**: SystemCapability.FileManagement.UserFileService @@ -157,18 +165,19 @@ Saves one or more images or videos in a **photoPicker** page. This API uses a pr **Example** ```ts -async function example() { - try { +async function 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) => { console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); - }).catch((err) => { - console.error('PhotoViewPicker.save failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('PhotoViewPicker.save failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -177,7 +186,7 @@ async function example() { save(option: PhotoSaveOptions, callback: AsyncCallback<Array<string>>) : void -Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves the file in the file manager, not in the Gallery. +Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves files in the file manager, not in **Gallery**. **System capability**: SystemCapability.FileManagement.UserFileService @@ -191,20 +200,21 @@ Saves one or more images or videos in a **photoPicker** page. This API uses an a **Example** ```ts -async function example() { +async function 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) => { if (err) { - console.error('PhotoViewPicker.save failed with err: ' + err); + console.error('PhotoViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -213,7 +223,7 @@ async function example() { save(callback: AsyncCallback<Array<string>>) : void -Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. The **save()** API saves the file in the file manager, not in the Gallery. +Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. The **save()** API saves files in the file manager, not in **Gallery**. **System capability**: SystemCapability.FileManagement.UserFileService @@ -226,25 +236,26 @@ Saves one or more images or videos in a **photoPicker** page. This API uses an a **Example** ```ts -async function example() { +async function example06() { try { let photoPicker = new picker.PhotoViewPicker(); - photoPicker.save((err, PhotoSaveResult) => { + photoPicker.save((err: BusinessError, PhotoSaveResult: Array) => { if (err) { - console.error('PhotoViewPicker.save failed with err: ' + err); + console.error('PhotoViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` ## DocumentViewPicker -Provides APIs for selecting and saving non-media files, for example, documents in a variety of formats. Before using the APIs of **DocumentViewPicker**, you need to create a **DocumentViewPicker** instance. +Provides the **DocumentViewPicker** object for selecting and saving documents in different formats. Before using the APIs of **DocumentViewPicker**, you need to create a **DocumentViewPicker** instance. **System capability**: SystemCapability.FileManagement.UserFileService @@ -277,17 +288,18 @@ Selects one or more documents in a **documentPicker** page. This API uses a prom **Example** ```ts -async function example() { +async function example07() { try { let DocumentSelectOptions = new picker.DocumentSelectOptions(); let documentPicker = new picker.DocumentViewPicker(); - documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => { + documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult: Array) => { console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); - }).catch((err) => { - console.error('DocumentViewPicker.select failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('DocumentViewPicker.select failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -310,19 +322,20 @@ Selects one or more documents in a **documentPicker** page. This API uses an asy **Example** ```ts -async function example() { +async function example08() { try { let DocumentSelectOptions = new picker.DocumentSelectOptions(); let documentPicker = new picker.DocumentViewPicker(); - documentPicker.select(DocumentSelectOptions, (err, DocumentSelectResult) => { + documentPicker.select(DocumentSelectOptions, (err: BusinessError, DocumentSelectResult: Array) => { if (err) { - console.error('DocumentViewPicker.select failed with err: ' + err); + console.error('DocumentViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -344,18 +357,19 @@ Selects one or more documents in a **documentPicker** page. This API uses an asy **Example** ```ts -async function example() { +async function example09() { try { let documentPicker = new picker.DocumentViewPicker(); - documentPicker.select((err, DocumentSelectResult) => { + documentPicker.select((err: BusinessError, DocumentSelectResult: Array) => { if (err) { - console.error('DocumentViewPicker.select failed with err: ' + err); + console.error('DocumentViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -384,18 +398,19 @@ Saves one or more documents in a **documentPicker** page. This API uses a promis **Example** ```ts -async function example() { +async function 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) => { console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); - }).catch((err) => { - console.error('DocumentViewPicker.save failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -418,20 +433,21 @@ Saves one or more documents in a **documentPicker** page. This API uses an async **Example** ```ts -async function example() { +async function 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) => { if (err) { - console.error('DocumentViewPicker.save failed with err: ' + err); + console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -453,18 +469,19 @@ Saves one or more documents in a **documentPicker** page. This API uses an async **Example** ```ts -async function example() { +async function example12() { try { let documentPicker = new picker.DocumentViewPicker(); - documentPicker.save((err, DocumentSaveResult) => { + documentPicker.save((err: BusinessError, DocumentSaveResult: Array) => { if (err) { - console.error('DocumentViewPicker.save failed with err: ' + err); + console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -504,17 +521,18 @@ Selects one or more audio files in an **audioPicker** page (currently, a **docum **Example** ```ts -async function example() { +async function example13() { try { let AudioSelectOptions = new picker.AudioSelectOptions(); let audioPicker = new picker.AudioViewPicker(); - audioPicker.select(AudioSelectOptions).then((AudioSelectResult) => { + audioPicker.select(AudioSelectOptions).then((AudioSelectResult: Array) => { console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); - }).catch((err) => { - console.error('AudioViewPicker.select failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -537,19 +555,20 @@ Selects one or more audio files in an **audioPicker** page (currently, a **docum **Example** ```ts -async function example() { +async function example14() { try { let AudioSelectOptions = new picker.AudioSelectOptions(); let audioPicker = new picker.AudioViewPicker(); - audioPicker.select(AudioSelectOptions, (err, AudioSelectResult) => { + audioPicker.select(AudioSelectOptions, (err: BusinessError, AudioSelectResult: Array) => { if (err) { - console.error('AudioViewPicker.select failed with err: ' + err); + console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -571,18 +590,19 @@ Selects one or more audio files in an **audioPicker** page (currently, a **docum **Example** ```ts -async function example() { +async function example15() { try { let audioPicker = new picker.AudioViewPicker(); - audioPicker.select((err, AudioSelectResult) => { + audioPicker.select((err: BusinessError, AudioSelectResult: Array) => { if (err) { - console.error('AudioViewPicker.select failed with err: ' + err); + console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -610,18 +630,19 @@ Saves one or more audio files in an **audioPicker** page (currently, a **documen **Example** ```ts -async function example() { +async function 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) => { console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)) - }).catch((err) => { - console.error('AudioViewPicker.save failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('AudioViewPicker.save failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -644,20 +665,21 @@ Saves one or more audio files in an **audioPicker** page (currently, a **documen **Example** ```ts -async function example() { +async function 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) => { if (err) { - console.error('AudioViewPicker.save failed with err: ' + err); + console.error('AudioViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -679,18 +701,19 @@ Saves one or more audio files in an **audioPicker** page (currently, a **documen **Example** ```ts -async function example() { +async function example18() { try { let audioPicker = new picker.AudioViewPicker(); - audioPicker.save((err, AudioSaveResult) => { + audioPicker.save((err: BusinessError, AudioSaveResult: Array) => { if (err) { - console.error('AudioViewPicker.save failed with err: ' + err); + console.error('AudioViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -715,8 +738,8 @@ Defines the options for selecting images or videos. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | -------------------------------- | -| MIMEType? | [PhotoViewMIMETypes](#photoviewmimetypes) | No | Available media file types. **IMAGE_VIDEO_TYPE** is used by default.| -| maxSelectNumber? | number | No | Maximum number of media files to select. The default value is **50**, and the maximum value is **500**. | +| MIMEType | [PhotoViewMIMETypes](#photoviewmimetypes) | No | Available media file types. **IMAGE_VIDEO_TYPE** is used by default.| +| maxSelectNumber | number | No | Maximum number of media files to select. The default value is **50**, and the maximum value is **500**. | ## PhotoSelectResult @@ -737,14 +760,20 @@ Defines the options for saving images or videos. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | No | Names of the files to save. If this parameter is not specified, the user needs to enter the file names.| +| newFileNames | Array<string> | No | Names of the files to save. If this parameter is not specified, the user needs to enter the file names.| ## DocumentSelectOptions -Defines the options for selecting documents. Currently, this parameter cannot be configured. +Defines the options for selecting documents. **System capability**: SystemCapability.FileManagement.UserFileService +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------- | ---- | -------------------------------- | +| maxSelectNumber10+ | number | No | Maximum number of files or directories that can be selected.
Value range: 1–500
Maximum value: **500** | +| defaultFilePathUri10+ | string | No | Path of the file or directory to select.| +| fileSuffixFilters10+ | Array<string> | No | File name extensions of the documents to select.| + ## DocumentSaveOptions Defines the options for saving documents. @@ -753,7 +782,9 @@ Defines the options for saving documents. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | No | Names of the documents to save. If this parameter is not specified, the user needs to enter the document names. | +| newFileNames | Array<string> | No | Names of the documents to save. If this parameter is not specified, the user needs to enter the document names. | +| defaultFilePathUri10+ | string | No | Path of the file or directory to save.| +| fileSuffixChoices10+ | Array<string> | No | File name extensions of the documents to save.| ## AudioSelectOptions @@ -769,4 +800,4 @@ Defines the options for saving audio files. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | No | Name of the audio files to save. If this parameter is not specified, the user needs to enter the file names.| +| newFileNames | Array<string> | No | Name of the audio files to save. If this parameter is not specified, the user needs to enter the file names.|