• 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.
4
5The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding picker instance and pass in **saveOptions**. No permission is required if your application uses **FilePicker** to access files.
6
7Currently, all the **save()** behaviors of **FilePicker** can be perceived by users. Specifically, **FilePicker** is started to save the files to a directory managed by **FileManager**. The files are isolated from the assets managed by **Gallery** and cannot be viewed in **Gallery**.
8
9To enable the saved image or video to be viewed in **Gallery**, [create the media asset using a security component](../media/medialibrary/photoAccessHelper-resource-guidelines.md#creating-a-media-asset-using-a-security-component).
10
11
12## Saving Images or Videos
13
14For example, select an image from **Gallery** and save it.
15
161. Import the [picker](../reference/apis-core-file-kit/js-apis-file-picker.md), [fs](../reference/apis-core-file-kit/js-apis-file-fs.md), and [photoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md) modules.
17
18   ```ts
19   import picker from '@ohos.file.picker';
20   import fs from '@ohos.file.fs';
21   import photoAccessHelper from '@ohos.file.photoAccessHelper';
22   ```
23
242. Use [select()](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#select) to select an image from the device and use a global variable to hold the returned URI.
25
26   ```ts
27   import photoAccessHelper from '@ohos.file.photoAccessHelper';
28   import { BusinessError } from '@ohos.base';
29
30   let selectUris: Array<string> = [];
31       try {
32           let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
33        	PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
34           PhotoSelectOptions.maxSelectNumber = 1;
35           let photoPicker = new photoAccessHelper.PhotoViewPicker();
36           photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
37               selectUris = PhotoSelectResult.photoUris;
38               console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
39           }).catch((err: BusinessError) => {
40               console.error(`PhotoViewPicker.select failed with err: ${err.code}, ${err.message}`);
41           });
42       } catch (error) {
43           let err: BusinessError = error as BusinessError;
44           console.error(`PhotoViewPicker failed with err: ${err.code}, ${err.message}`);
45       }
46   ```
47
483. Use [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save) to start the FilePicker page to save the image. After the user selects the destination folder, the image is saved. A global variable holding the URI of the image is returned.
49
50   The permission on the URI returned by **save()** is read/write. Further file operations can be performed based on the URI.
51
52   ```ts
53   import picker from '@ohos.file.picker';
54   import { BusinessError } from '@ohos.base';
55
56   let saveUris: Array<string> = [];
57   try {
58       const photoSaveOptions = new picker.PhotoSaveOptions(); // Create a photoSaveOptions instance.
59       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.
60       const photoViewPicker = new picker.PhotoViewPicker();
61       try {
62           let photoSaveResult = await photoViewPicker.save(photoSaveOptions);
63           if (photoSaveResult != undefined) {
64               saveUris = photoSaveResult;
65               console.info('photoViewPicker.save to file succeed and uris are:' + photoSaveResult);
66           }
67       } catch (error) {
68           let err: BusinessError = error as BusinessError;
69           console.error(`[picker] Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
70       }
71   } catch (error) {
72       let err: BusinessError = error as BusinessError;
73       console.info("[picker] photoViewPickerSave error = " + JSON.stringify(err));
74   }
75   ```
76
774. Use [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to select the file and save it. The FDs of the file selected and the file saved are returned. Note that the permission is **fs.OpenMode.READ_ONLY** in the select API and **fs.OpenMode.WRITE_ONLY** in the save API. Use [fs.copyFileSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fscopyfilesync) to copy the file. Then, use **close()** to close the file selected and the file saved.
78
79   ```ts
80   import fs from '@ohos.file.fs';
81   import { BusinessError } from '@ohos.base';
82
83   try {
84   	let photoSelect = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
85       let photoSave = fs.openSync(saveUris[0], fs.OpenMode.WRITE_ONLY);
86       fs.copyFileSync(photoSelect.fd, photoSave.fd);
87       fs.close(photoSelect);
88       fs.close(photoSave);
89   } catch (error) {
90       let err: BusinessError = error as BusinessError;
91       console.info("[picker] Photo Save error = " + JSON.stringify(err));
92   }
93   ```
94
95## Saving Documents
96
971. Import the **picker** and **fs** modules.
98
99   ```ts
100   import picker from '@ohos.file.picker';
101   import fs from '@ohos.file.fs';
102   import { BusinessError } from '@ohos.base';
103   ```
104
1052. Create a **documentSaveOptions** instance.
106
107   ```ts
108   const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance.
109   documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the name of the document to save.
110   documentSaveOptions.fileSuffixChoices = ['.png', '.txt', '.mp4']; // (Optional) Types of the documents to save.
111   ```
112
1133. Create a **documentViewPicker** instance, and use [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save-3) to start 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.<br>The permission on the URI returned by **save()** is read/write. Further file operations can be performed based on the URI. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to hold the URI and use a button to open the file.
114
115   ```ts
116import { BusinessError } from '@ohos.base';
117
118   let uris: Array<string> = [];
119const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
120   documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
121     uris = documentSaveResult;
122     console.info('documentViewPicker.save to file succeed and uris are:' + uris);
123   }).catch((err: BusinessError) => {
124     console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
125   })
126   ```
127
1284. After the application UI is returned from **FilePicker**, use a button to trigger the application's API. Use [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to open a document based on the URI. After the document is opened, the FD is returned. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
129
130   ```ts
131   import fs from '@ohos.file.fs';
132
133   const uri = '';
134   let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
135   console.info('file fd: ' + file.fd);
136   ```
137
1385. Use [fs.writeSync](../reference/apis-core-file-kit/js-apis-file-fs.md#writesync) to modify the document based on the FD, and use **closeSync()** to close the document.
139
140   ```ts
141   import fs from '@ohos.file.fs';
142
143   let writeLen: number = fs.writeSync(file.fd, 'hello, world');
144   console.info('write data to file succeed and size is:' + writeLen);
145   fs.closeSync(file);
146   ```
147
148## Saving Audio Clips
149
1501. Import the **picker** and **fs** modules.
151
152   ```ts
153   import picker from '@ohos.file.picker';
154   import fs from '@ohos.file.fs';
155   import { BusinessError } from '@ohos.base';
156   ```
157
1582. Create an **audioSaveOptions** instance.
159
160   ```ts
161   const audioSaveOptions = new picker.AudioSaveOptions(); // Create an audioSaveOptions instance.
162   audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the name of the audio file to save.
163   ```
164
1653. Create an **audioViewPicker** instance, and use [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save-6) to start the FilePicker page to save the audio clip. After the user selects the destination folder, the audio clip is saved and the URI of the audio clip saved is returned.<br>The permission on the URI returned by **save()** is read/write. Further file operations can be performed based on the URI. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to hold the URI and use a button to open the audio clip.
166
167   ```ts
168   let uri: string = '';
169   const audioViewPicker = new picker.AudioViewPicker();
170   audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array<string>) => {
171     uri = audioSelectResult[0];
172     console.info('audioViewPicker.save to file succeed and uri is:' + uri);
173   }).catch((err: BusinessError) => {
174     console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
175   })
176   ```
177
1784. After the application UI is returned from **FilePicker**, use a button to trigger the application's API. Use [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to open an audio clip based on the URI. After the audio clip is opened, the FD is returned. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
179
180   ```ts
181   let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
182   console.info('file fd: ' + file.fd);
183   ```
184
1855. Use [fs.writeSync](../reference/apis-core-file-kit/js-apis-file-fs.md#writesync) to modify the audio clip based on the FD, and use **closeSync()** to close the audio clip.
186
187   ```ts
188   let writeLen = fs.writeSync(file.fd, 'hello, world');
189   console.info('write data to file succeed and size is:' + writeLen);
190   fs.closeSync(file);
191   ```
192
193<!--no_check-->