1# Sharing an Application File
2
3An application can share a file with another application based on the file descriptor (FD) or uniform resource identifier (URI) of the file.
4
5- URI-based file sharing: You can use [wantConstant.Flags](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#flags) to specify the read or read/write permission on the file for the target application (application with which the file is shared). The target application can call [fs.open](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopen) to open the file based on the URI and perform read and write operations. Currently, only temporary authorization is supported. The permission on the shared file is revoked once the target application exits.
6
7- FD-based sharing: You can use **open()** of the ohos.file.fs module to specify the read or read/write permission on the file for the target application. After obtaining the FD from Want, the target application can call [ohos.file.fs](../reference/apis-core-file-kit/js-apis-file-fs.md) APIs to read and write the file.
8After the FD of a shared file is closed, the target application can no longer open the shared file. Therefore, FD-based file sharing is not recommended. This topic describes how to [share an application file](#sharing-an-application-file) and [use a shared file](#using-a-shared-file) based on the file URI.
9
10## Shareable Application Directories
11
12| Application Sandbox Path           | Physical Path                                                | Description              |
13| ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
14| /data/storage/el1/base             | /data/app/el1/\<currentUserId\>/base/\<PackageName\>         | Encrypted database directory under **/el1**.                 |
15| /data/storage/el2/base             | /data/app/el2/\<currentUserId\>/base/\<PackageName\>         | Encrypted database directory under **/el2**.                 |
16| /data/storage/el2/distributedfiles | /mnt/hmdfs/\<currentUserId\>/account/device_view/\<networkId\>/data/\<PackageName\> | Distributed data directory with an account under **/el2**.   |
17
18## File URI Specifications
19
20The file URIs are in the following format:
21
22  **file**://&lt;bundleName&gt;/&lt;path&gt;
23
24- **file**: indicates a file URI.
25
26- *bundleName*: specifies the owner of the file, that is, the application that shares the file.
27
28- *path*: specifies the application sandbox path of the file.
29
30## Sharing an Application File
31
32Before sharing an application file, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-application-file-paths).
33
341. Obtain the application sandbox path of the file and convert it into the file URI.
35
36   ```ts
37   import { UIAbility } from '@kit.AbilityKit';
38   import { fileUri } from '@kit.CoreFileKit';
39   import { window } from '@kit.ArkUI';
40
41   export default class EntryAbility extends UIAbility {
42     onWindowStageCreate(windowStage: window.WindowStage) {
43       // Obtain the application sandbox path of the file.
44       let pathInSandbox = this.context.filesDir + "/test1.txt";
45       // Convert the application sandbox path into a URI.
46       let uri = fileUri.getUriFromPath(pathInSandbox);
47       // The obtained URI is file://com.example.demo/data/storage/el2/base/files/test1.txt.
48     }
49   }
50   ```
51
522. Set the target application and grant permissions on the file.<br>
53   Use [startAbility](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start 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-ability-kit/js-apis-app-ability-want.md#properties).
54
55   > **NOTE**
56   >
57   > The write permission granted includes the read permission.
58
59   ```ts
60   import { fileUri } from '@kit.CoreFileKit';
61   import { window } from '@kit.ArkUI';
62   import { wantConstant } from '@kit.AbilityKit';
63   import { UIAbility } from '@kit.AbilityKit';
64   import { Want } from '@kit.AbilityKit';
65   import { BusinessError } from '@kit.BasicServicesKit';
66
67   export default class EntryAbility extends UIAbility {
68     onWindowStageCreate(windowStage: window.WindowStage) {
69       // Obtain the application sandbox path of the file.
70       let filePath = this.context.filesDir + '/test1.txt';
71       // Convert the application sandbox path into a URI.
72       let uri = fileUri.getUriFromPath(filePath);
73       let want: Want  = {
74         // Grant the read and write permissions on the shared file to the target application.
75         flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
76         // Set the implicit startup rule for the target application.
77         action: 'ohos.want.action.sendData',
78         uri: uri,
79         type: 'text/plain'
80       }
81       this.context.startAbility(want)
82         .then(() => {
83           console.info('Invoke getCurrentBundleStats succeeded.');
84         })
85         .catch((err: BusinessError) => {
86           console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
87         });
88     }
89     // ...
90   }
91   ```
92**Figure 1** Example
93
94   ![share-app-file](figures/share-app-file.png)
95
96## Using a Shared File
97
98In the [**module.json5** file](../quick-start/module-configuration-file.md) of the target application, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by others and set **uris** to the type of the URI to receive. In the following example, the target application receives only .txt files with **scheme** of **file**.
99
100```json
101{
102  "module": {
103    ...
104    "abilities": [
105      {
106        ...
107        "skills": [
108          {
109            ...
110            "actions": [
111              "ohos.want.action.sendData"
112            ],
113            "uris": [
114              {
115                "scheme": "file",
116                "type": "text/plain"
117              }
118           ]
119          }
120        ]
121      }
122    ]
123  }
124}
125```
126
127After the UIAbility starts, the target application obtains want information via [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant).
128
129After obtaining the URI of the shared file from **want**, the target application can call **fs.open** to open the file and then read and write the file.
130
131```ts
132// xxx.ets
133import { fileIo as fs } from '@kit.CoreFileKit';
134import { Want } from '@kit.AbilityKit';
135import { BusinessError } from '@kit.BasicServicesKit';
136
137function getShareFile() {
138  try {
139    let want: Want = {}; // Change the value to the want information passed by the application that shares the file.
140
141    // Obtain the uri field from the want information.
142    let uri = want.uri;
143    if (uri == null || uri == undefined) {
144      console.info('uri is invalid');
145      return;
146    }
147    try {
148      // 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.
149      let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
150      console.info('open file successfully!');
151    } catch (err) {
152      let error: BusinessError = err as BusinessError;
153      console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`);
154    }
155  } catch (error) {
156    let err: BusinessError = error as BusinessError;
157    console.error(`Invoke openSync failed, code is ${err.code}, message is ${err.message}`);
158  }
159}
160```
161