• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Saving User Files
2
3When a user needs to download a file from the Internet or save a file to another directory, use **FilePicker** to save the file. Pay attention to the following key points:
4
5**Permission Description**
6
7- The read and write permissions on the file URI granted by Picker is temporary by default, and will be automatically invalidated once the application exits.
8- You can persist the permissions on the URI. For details, see [Persisting a Temporary Permission Granted by Picker](file-persistPermission.md#persisting-a-temporary-permission-granted-by-picker). (This operation is available only for 2-in-1 devices.)
9- No permission is required if your application uses Picker to save audio clips, images, videos, and document files.
10
11**System Isolation Description**
12
13- The files saved by the Picker are stored in the specified directory. They are isolated from the assets managed by **Gallery** and cannot be viewed in **Gallery**.
14- To save images and videos to **Gallery**, [use a security component](../media/medialibrary/photoAccessHelper-savebutton.md).
15
16## Saving Images or Videos
17
18[PhotoViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpickerdeprecated) will not be maintained in later versions. You are advised to use [Media Library Kit](../media/medialibrary/photoAccessHelper-savebutton.md) to save media assets.
19
20If the security component cannot be called to save images and videos in your development, use [PhotoAccessHelper.showAssetsCreationDialog](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#showassetscreationdialog12) to save images and videos.
21
22## Saving Documents
23
241. Import modules.
25
26   ```ts
27   import { picker } from '@kit.CoreFileKit';
28   import { fileIo as fs } from '@kit.CoreFileKit';
29   import { BusinessError } from '@kit.BasicServicesKit';
30   import { common } from '@kit.AbilityKit';
31   ```
32
332. Configure the save options.
34
35   ```ts
36   // Create a documentSaveOptions instance.
37   const documentSaveOptions = new picker.DocumentSaveOptions();
38   // (Optional) Name of the file to save. The default value is empty.
39   documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"];
40   // (Optional) Type of the document to save. The value is in ['Description|File name extensions'] format. To save all files, use 'All files (*.*)|.*'. If there are multiple file name extensions (a maximum of 100 extensions can be filtered), the first one is used by default. If this parameter is not specified, no extension is filtered by default.
41   documentSaveOptions.fileSuffixChoices = ['Document|.txt', '.pdf'];
42   ```
43
443. Create a [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#constructor12) instance, and call [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save) to start the FilePicker page to save the document.
45
46   ```ts
47   let uris: Array<string> = [];
48   // Ensure that getContext(this) returns UIAbilityContext.
49   let context = getContext(this) as common.Context;
50   const documentViewPicker = new picker.DocumentViewPicker(context);
51   documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
52     uris = documentSaveResult;
53     console.info('documentViewPicker.save to file succeed and uris are:' + uris);
54   }).catch((err: BusinessError) => {
55     console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
56   })
57   ```
58
59   > **NOTE**
60   >
61   > 1. URI storage:<br>
62   > - Avoid directly using a URI in the Picker callback.<br>
63   > - Define a global variable to save the URI for future use.<br>
64   >
65   > 2. Quick saving:<br>
66   > - Directly access the download directory in [DOWNLOAD mode](#saving-files-to-the-download-directory).<br>
67
684. After the application UI is returned from FilePicker, call [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to open a document based on the URI. The file descriptor (FD) is returned after the document is opened.
69
70   ```ts
71   const uri = '';
72   // Note that the permission specified by the mode parameter of fs.openSync() is fs.OpenMode.READ_WRITE.
73   let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
74   console.info('file fd: ' + file.fd);
75   ```
76
775. Call [fs.writeSync](../reference/apis-core-file-kit/js-apis-file-fs.md#writesync) to modify the document based on the FD, and call **fs.closeSync()** to close the FD.
78
79   ```ts
80   let writeLen: number = fs.writeSync(file.fd, 'hello, world');
81   console.info('write data to file succeed and size is:' + writeLen);
82   fs.closeSync(file);
83   ```
84
85## Saving Audio Clips
86
871. Import modules.
88
89   ```ts
90   import { picker } from '@kit.CoreFileKit';
91   import { fileIo as fs } from '@kit.CoreFileKit';
92   import { BusinessError } from '@kit.BasicServicesKit';
93   import { common } from '@kit.AbilityKit';
94   ```
95
962. Configure the save options.
97
98   ```ts
99   const audioSaveOptions = new picker.AudioSaveOptions();
100   // (Optional) Name of the document to save.
101   audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3'];
102   ```
103
1043. Create an [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) instance and call [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save-5) to start the FilePicker page to save the audio clip.
105
106   ```ts
107   let uri: string = '';
108   // Ensure that getContext(this) returns UIAbilityContext.
109   let context = getContext(this) as common.Context;
110   const audioViewPicker = new picker.AudioViewPicker(context);
111   audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array<string>) => {
112     uri = audioSelectResult[0];
113     console.info('audioViewPicker.save to file succeed and uri is:' + uri);
114   }).catch((err: BusinessError) => {
115     console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
116   })
117   ```
118
119   > **NOTE**
120   >
121   > 1. URI storage:<br>
122   > - Avoid directly using a URI in the Picker callback.<br>
123   > - Define a global variable to save the URI for future use.<br>
124   >
125   > 2. Quick saving:<br>
126   > - Directly access the download directory in [DOWNLOAD mode](#saving-files-to-the-download-directory).<br>
127
1284. After the application UI is returned from FilePicker, call [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to open an audio clip based on the URI. The FD is returned after the audio clip is opened.
129
130   ```ts
131   // Note that the permission specified by the mode parameter of fs.openSync() is fileIo.OpenMode.READ_WRITE.
132   let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
133   console.info('file fd: ' + file.fd);
134   ```
135
1365. Call [fs.writeSync](../reference/apis-core-file-kit/js-apis-file-fs.md#writesync) to modify the document based on the FD, and call **fs.closeSync()** to close the FD.
137
138   ```ts
139   let writeLen = fs.writeSync(file.fd, 'hello, world');
140   console.info('write data to file succeed and size is:' + writeLen);
141   fs.closeSync(file);
142
143   ```
144
145## Saving Files to the Download Directory
146
147**Characteristics**
148
149- The directory is automatically created in `Download/bundle name/`.
150- Files can be directly saved without file selection.
151- You can create files under the returned URI that has persistent permissions.
152
1531. Import modules.
154
155   ```ts
156   import { fileUri, picker } from '@kit.CoreFileKit';
157   import { fileIo as fs } from '@kit.CoreFileKit';
158   import { BusinessError } from '@kit.BasicServicesKit';
159   import { common } from '@kit.AbilityKit';
160   ```
161
1622. Configure the download mode.
163
164   ```ts
165   const documentSaveOptions = new picker.DocumentSaveOptions();
166   // Set pickerMode to DOWNLOAD, which takes precedence over the settings in documentSaveOptions.
167   documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;
168   ```
169
1703. Save the file to the **Download** directory.
171
172   ```ts
173   let uri: string = '';
174   // Ensure that getContext(this) returns UIAbilityContext.
175   let context = getContext(this) as common.Context;
176   const documentViewPicker = new picker.DocumentViewPicker(context);
177   const documentSaveOptions = new picker.DocumentSaveOptions();
178   documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;
179   documentViewPicker.save(documentSaveOptions ).then((documentSaveResult: Array<string>) => {
180     uri = documentSaveResult[0];
181     console.info('documentViewPicker.save succeed and uri is:' + uri);
182     const testFilePath = new fileUri.FileUri(uri + '/test.txt').path;
183     const file = fs.openSync(testFilePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
184     fs.writeSync(file.fd, 'Hello World!');
185     fs.closeSync(file.fd);
186   }).catch((err: BusinessError) => {
187     console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
188   })
189   ```
190