• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Saving User Files
2<!--Kit: Core File Kit-->
3<!--Subsystem: FileManagement-->
4<!--Owner: @wang_zhangjun; @zhuangzhuang-->
5<!--Designer: @wang_zhangjun; @zhuangzhuang; @renguang1116-->
6<!--Tester: @liuhonggang123; @yue-ye2; @juxiaopang-->
7<!--Adviser: @foryourself-->
8
9When 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:
10
11**Permission Description**
12
13- 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.
14- 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).
15- No permission is required if your application uses Picker to save audio clips, images, videos, and document files.
16
17**System Isolation Description**
18
19- 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**.
20- To save images and videos to Gallery, [use the SaveButton](../media/medialibrary/photoAccessHelper-savebutton.md#creating-a-media-asset-using-savebutton).
21
22## Saving Images or Videos
23
24[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.
25
26If the security component cannot be called to save images and videos in your development, use [PhotoAccessHelper.showAssetsCreationDialog](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper-PhotoAccessHelper.md#showassetscreationdialog12) to save images and videos.
27
28## Saving Documents
29
301. Import modules.
31
32   ```ts
33   import { picker } from '@kit.CoreFileKit';
34   import { fileIo as fs } from '@kit.CoreFileKit';
35   import { BusinessError } from '@kit.BasicServicesKit';
36   import { common } from '@kit.AbilityKit';
37   ```
38
392. Configure the save options.
40
41   ```ts
42   // Create a documentSaveOptions instance.
43   const documentSaveOptions = new picker.DocumentSaveOptions();
44   // (Optional) Name of the file to save. The default value is empty.
45   documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"];
46   // Optional. Specify the path of the file or directory to save.
47   documentSaveOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test";
48   // (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.
49   documentSaveOptions.fileSuffixChoices = ['Document|.txt', '.pdf'];
50   ```
51
523. 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.
53
54   ```ts
55   let uris: Array<string> = [];
56   // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
57   let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
58   const documentViewPicker = new picker.DocumentViewPicker(context);
59   documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
60     uris = documentSaveResult;
61     console.info('documentViewPicker.save to file succeed and uris are:' + uris);
62   }).catch((err: BusinessError) => {
63     console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
64   })
65   ```
66
67   > **NOTE**
68   >
69   > 1. URI storage:
70   >	 - You should avoid directly using a URI in the Picker callback.
71   >	 - You are advised to define a global variable to save the URI for future use.
72   >
73   > 2. Quick saving:
74   > 	- You can directly access the download directory in [DOWNLOAD mode](#saving-files-to-the-download-directory).
75
764. After the application UI is returned from FilePicker, you can call [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to open a document based on the URI. The FD is returned after the document is opened.
77
78   ```ts
79   const uri = '';
80   // Note that the permission specified by the mode parameter of fs.openSync() is fs.OpenMode.READ_WRITE.
81   let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
82   console.info('file fd: ' + file.fd);
83   ```
84
855. 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.
86
87   ```ts
88   let writeLen: number = fs.writeSync(file.fd, 'hello, world');
89   console.info('write data to file succeed and size is:' + writeLen);
90   fs.closeSync(file);
91   ```
92
93## Saving Audio Clips
94
951. Import modules.
96
97   ```ts
98   import { picker } from '@kit.CoreFileKit';
99   import { fileIo as fs } from '@kit.CoreFileKit';
100   import { BusinessError } from '@kit.BasicServicesKit';
101   import { common } from '@kit.AbilityKit';
102   ```
103
1042. Configure the save options.
105
106   ```ts
107   const audioSaveOptions = new picker.AudioSaveOptions();
108   // (Optional) Name of the document to save.
109   audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3'];
110   ```
111
1123. 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.
113
114   ```ts
115   let uri: string = '';
116   // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
117   let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
118   const audioViewPicker = new picker.AudioViewPicker(context);
119   audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array<string>) => {
120     uri = audioSelectResult[0];
121     console.info('audioViewPicker.save to file succeed and uri is:' + uri);
122   }).catch((err: BusinessError) => {
123     console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
124   })
125   ```
126
127   > **NOTE**
128   >
129   > 1. URI storage:
130   > 	- You should avoid directly using a URI in the Picker callback.
131   > 	- You are advised to define a global variable to save the URI for future use.
132   >
133   > 2. Quick saving:
134   > 	- You can directly access the download directory in [DOWNLOAD mode](#saving-files-to-the-download-directory).
135
1364. 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.
137
138   ```ts
139   // Note that the permission specified by the mode parameter of fs.openSync() is fileIo.OpenMode.READ_WRITE.
140   let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
141   console.info('file fd: ' + file.fd);
142   ```
143
1445. 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.
145
146   ```ts
147   let writeLen = fs.writeSync(file.fd, 'hello, world');
148   console.info('write data to file succeed and size is:' + writeLen);
149   fs.closeSync(file);
150
151   ```
152
153## Saving Files to the Download Directory
154
155**Characteristics**
156
157- The directory is automatically created in `Download/bundle name/`.
158- Files can be directly saved without file selection.
159- You can create files under the returned URI that has persisting permissions.
160
1611. Import modules.
162
163   ```ts
164   import { fileUri, picker } from '@kit.CoreFileKit';
165   import { fileIo as fs } from '@kit.CoreFileKit';
166   import { BusinessError } from '@kit.BasicServicesKit';
167   import { common } from '@kit.AbilityKit';
168   ```
169
1702. Configure the download mode.
171
172   ```ts
173   const documentSaveOptions = new picker.DocumentSaveOptions();
174   // Set pickerMode to DOWNLOAD, which takes precedence over the settings in documentSaveOptions.
175   documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;
176   ```
177
1783. Save the file to the **Download** directory.
179
180   ```ts
181   let uri: string = '';
182   // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
183   let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
184   const documentViewPicker = new picker.DocumentViewPicker(context);
185   const documentSaveOptions = new picker.DocumentSaveOptions();
186   documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;
187   documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
188     uri = documentSaveResult[0];
189     console.info('documentViewPicker.save succeed and uri is:' + uri);
190     const testFilePath = new fileUri.FileUri(uri + '/test.txt').path;
191     const file = fs.openSync(testFilePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
192     fs.writeSync(file.fd, 'Hello World!');
193     fs.closeSync(file.fd);
194   }).catch((err: BusinessError) => {
195     console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
196   })
197   ```
198