• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.fileshare (File Sharing) (System API)
2<!--Kit: Core File Kit-->
3<!--Subsystem: FileManagement-->
4<!--Owner: @lvzhenjie; @hongjin-li_admin-->
5<!--Designer: @chenxi0605; @JerryH1011-->
6<!--Tester: @leiyuqian-->
7<!--Adviser: @foryourself-->
8
9The **fileShare** module provides APIs for granting the access permissions on a user file to another application based on the file Uniform Resource Identifier (URI). Then, the authorized application can access the file by using the [@ohos.file.fs](js-apis-file-fs.md) APIs.
10
11> **NOTE**
12>
13> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
14> - This topic describes only the system APIs provided by the module. For details about its public APIs, see [@ohos.fileshare](js-apis-fileShare-sys.md).
15
16## Modules to Import
17
18```ts
19import  { fileShare } from '@kit.CoreFileKit';
20```
21
22## fileShare.grantUriPermission
23
24grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags, callback: AsyncCallback&lt;void&gt;): void
25
26Grants the permissions on a user file to an application. This API uses an asynchronous callback to return the result.
27
28**Required permissions**: ohos.permission.WRITE_MEDIA
29
30**System API**: This is a system API.
31
32**System capability**: SystemCapability.FileManagement.AppFileService
33
34**Parameters**
35
36| Name| Type| Mandatory| Description|
37| ------ |---------| ---- |-----------|
38| uri   | string| Yes  | URI of the file under user directory.|
39| bundleName   | string| Yes  | Application to be granted with the permissions.  |
40| flag   | [wantConstant.Flags](../apis-ability-kit/js-apis-app-ability-wantConstant.md#flags) | Yes  | Permissions to grant.    |
41 | callback | AsyncCallback&lt;void&gt;| Yes   | Callback used to return the result.|
42
43**Error codes**
44
45For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
46
47| ID| Error Message|
48| ------ | ------- |
49| 201 | Permission verification failed. |
50| 202 | The caller is not a system application. |
51| 401 | The input parameter is invalid. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
52| 143000001 | IPC error. |
53
54**Example**
55
56  ```ts
57  import { wantConstant } from '@kit.AbilityKit';
58  import { BusinessError } from '@kit.BasicServicesKit';
59  let uri: string = 'file://docs/storage/Users/currentUser/Document/1.txt';  // You are advised to use the system API fileUri.getUriFromPath("Sandbox path") to generate a URI.;
60  let bundleName: string = 'com.demo.test';
61  try {
62    fileShare.grantUriPermission(uri, bundleName, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION |
63      wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION, (err: BusinessError) => {
64      if (err) {
65        console.error("grantUriPermission failed with error: " + JSON.stringify(err));
66        return;
67      }
68      console.info("grantUriPermission success!");
69    });
70  } catch (err) {
71    let error: BusinessError = err as BusinessError;
72    console.error("grantUriPermission failed with error:" + JSON.stringify(error));
73  }
74  ```
75
76## fileShare.grantUriPermission
77
78grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags): Promise&lt;void&gt;
79
80Grants the permissions on a user file to an application. This API uses a promise to return the result.
81
82**Required permissions**: ohos.permission.WRITE_MEDIA
83
84**System API**: This is a system API.
85
86**System capability**: SystemCapability.FileManagement.AppFileService
87
88**Parameters**
89
90| Name| Type| Mandatory| Description       |
91| ------ |-------| ---- |-----------|
92| uri   | string| Yes  | URI of the file under user directory.|
93| bundleName   | string| Yes  | Application to be granted with the permissions.  |
94| flag   | [wantConstant.Flags](../apis-ability-kit/js-apis-app-ability-wantConstant.md#flags) | Yes  | Permissions to grant.    |
95
96**Return value**
97
98  | Type                          | Description        |
99  | ---------- | ---------- |
100  | Promise&lt;void&gt; | Promise that returns no value.|
101
102**Error codes**
103
104For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
105
106| ID| Error Message|
107| ------- | ---------- |
108| 201 | Permission verification failed. |
109| 202 | The caller is not a system application. |
110| 401 | The input parameter is invalid. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
111| 143000001 | IPC error. |
112
113**Example**
114
115  ```ts
116  import { wantConstant } from '@kit.AbilityKit';
117  import { BusinessError } from '@kit.BasicServicesKit';
118  let uri: string = 'file://docs/storage/Users/currentUser/Document/1.txt'; // You are advised to use the system API fileUri.getUriFromPath("Sandbox path") to generate a URI.;
119  let bundleName: string = 'com.demo.test';
120  try {
121    fileShare.grantUriPermission(uri, bundleName, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION |
122      wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION).then(() => {
123      console.info("grantUriPermission success!");
124    }).catch((error: BusinessError) => {
125      console.error("grantUriPermission failed with error:" + JSON.stringify(error));
126    });
127  } catch (err) {
128    let error: BusinessError = err as BusinessError;
129    console.error("grantUriPermission failed with error:" + JSON.stringify(error));
130  }
131  ```
132
133## fileShare.checkPathPermission<sup>15+</sup>
134
135checkPathPermission(tokenID: number, policies: Array&lt;PathPolicyInfo&gt;, policyType: PolicyType): Promise&lt;Array&lt;boolean&gt;&gt;
136
137Checks whether the selected files or directories have temporary or persistent permissions. This API uses a promise to return the result.
138
139**Required permissions**: ohos.permission.CHECK_SANDBOX_POLICY
140
141**System API**: This is a system API.
142
143**System capability**: SystemCapability.FileManagement.AppFileService.FolderAuthorization
144
145**Parameters**
146
147| Name| Type| Mandatory| Description|
148| -------- |-------| -------- |----------|
149| tokenID| number | Yes| Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](../apis-ability-kit/js-apis-bundleManager-applicationInfo.md).|
150| policies| Array&lt;[PathPolicyInfo](js-apis-fileShare.md#pathpolicyinfo15)> | Yes| Array of permission policies. The maximum number of policies is 500.|
151| policyType| [PolicyType](js-apis-fileShare.md#policytype15) | Yes| Policy type to check, which can be a temporary or persistent permission.|
152
153**Return value**
154
155|Type|Description|
156| ------ | ------ |
157| Promise&lt;Array&lt;boolean&gt;&gt; | Promise used to return the result. The value **true** means that a policy type is used; the value **false** means the opposite.|
158
159**Error codes**
160
161For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
162
163| ID   | Error Message      |
164|----------| --------- |
165| 201      | Permission verification failed, usually the result returned by VerifyAccessToken.|
166| 202      | The caller is not a system application.|
167| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
168| 801      | Capability not supported. |
169
170**Example**
171
172  ```ts
173  import { BusinessError } from '@kit.BasicServicesKit';
174  import { fileShare } from '@kit.CoreFileKit';
175
176  async function checkPersistentPermissionExample() {
177    try {
178      let pathPolicyInfo1: fileShare.PathPolicyInfo = {
179        path: "/storage/Users/currentUser/Documents/1.txt",
180        operationMode: fileShare.OperationMode.READ_MODE,
181      }
182      let pathPolicyInfo2: fileShare.PathPolicyInfo = {
183        path: "/storage/Users/currentUser/Desktop/2.txt",
184        operationMode: fileShare.OperationMode.READ_MODE,
185      }
186
187      let policies: Array<fileShare.PathPolicyInfo> = [pathPolicyInfo1, pathPolicyInfo2];
188      let policyType: fileShare.PolicyType = fileShare.PolicyType.PERSISTENT_TYPE;
189      let tokenid = 537688848; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application.
190
191      fileShare.checkPathPermission(tokenid, policies, policyType).then((result:Array<boolean>) => {
192        for (let x of result) {
193          console.info('check permission result is', x);
194        }
195      })
196      console.info("checkPathPermission finish");
197    }
198    catch (error) {
199      console.info(error.code + 'checkPathPermission error' + error.message);
200    }
201  }
202  ```
203
204## fileShare.grantUriPermission<sup>20+</sup>
205
206grantUriPermission(policies: Array&lt;PolicyInfo&gt;, targetBundleName: string, appCloneIndex: number): Promise&lt;void&gt;
207
208Grants temporary permissions on a file to an application. This API uses a promise to return the result.
209
210**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
211
212**System API**: This is a system API.
213
214**System capability**: SystemCapability.FileManagement.AppFileService.FolderAuthorization
215
216**Parameters**
217
218| Name| Type| Mandatory| Description|
219| -------- |-------| -------- |----------|
220| policies| Array&lt;[PolicyInfo](js-apis-fileShare.md#policyinfo11)> | Yes| Array of permission policies. The maximum number of policies is 500.|
221| targetBundleName| string | Yes| Bundle name of the target application.|
222| appCloneIndex| number | Yes| Index of the cloned application. The value **0** indicates the application itself.|
223
224**Return value**
225
226|Type|Description|
227| ------ | ------ |
228| Promise&lt;void&gt; | Promise that returns no value.|
229
230**Error codes**
231
232For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [File Management Error Codes](errorcode-filemanagement.md).
233
234| ID   | Error Message      |
235|----------| --------- |
236| 201      | Permission verification failed, usually the result returned by VerifyAccessToken.|
237| 202      | The caller is not a system application.|
238| 801      | Capability not supported. |
239| 13900001      | Operation not permitted. |
240| 13900011      | Out of memory. |
241
242**Example**
243
244  ```ts
245  import { BusinessError } from '@kit.BasicServicesKit';
246  import { fileShare } from '@kit.CoreFileKit';
247
248  async function grantUriPermissionExample() {
249    try {
250      let uri = "file://docs/storage/Users/currentUser/Documents/1.txt";
251      let policyInfo: fileShare.PolicyInfo = {
252        uri: uri,
253        operationMode: fileShare.OperationMode.CREATE_MODE | fileShare.OperationMode.READ_MODE,
254      };
255      let policies: Array<fileShare.PolicyInfo> = [policyInfo];
256
257      fileShare.grantUriPermission(policies, "com.example.myapplicationtest", 0).then(() => {
258      }).catch((err: BusinessError<Array<fileShare.PolicyErrorResult>>) => {
259        console.error("grantUriPermission failed. Code: " +
260        err.code + ", message: " + err.message);
261      });
262    }
263    catch (error) {
264      console.info('grantUriPermission error, Code: ' + error.code + ', message: ' + error.message);
265    }
266  }
267  ```
268