save-user-file.md 9.4 KB
Newer Older
A
Annie_wang 已提交
1 2 3 4
# Saving User Files

When a user needs to download a file from the network to a local directory or save a user file into another directory, use **FilePicker** to save the file.

A
Annie_wang 已提交
5
The 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.
A
Annie_wang 已提交
6

A
Annie_wang 已提交
7
The **save()** method saves files in the file manager, not in **Gallery**.
A
Annie_wang 已提交
8

A
Annie_wang 已提交
9 10 11

## Saving Images or Video Files

A
Annie_wang 已提交
12 13
For example, select an image from **Gallery** and save it to the file manager.

A
Annie_wang 已提交
14
1. Import the [picker](../reference/apis/js-apis-file-picker.md), [fs](../reference/apis/js-apis-file-fs.md), [photoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md), and [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) modules.
A
Annie_wang 已提交
15 16 17

   ```ts
   import picker from '@ohos.file.picker';
A
Annie_wang 已提交
18
   import fs from '@ohos.file.fs';
A
Annie_wang 已提交
19 20
   import photoAccessHelper from '@ohos.file.photoAccessHelper';
   import dataSharePredicates from '@ohos.data.dataSharePredicates';
A
Annie_wang 已提交
21 22
   ```

A
Annie_wang 已提交
23
2. Obtain the thumbnail of the first image on the device. Before performing this operation, ensure that at least one image exists on the device.
A
Annie_wang 已提交
24 25

   ```ts
A
Annie_wang 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
   const context = getContext(this);
   let photoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);

   let pixelmapArrayBuffer;
   async getPixelmap() {
      try {
         let predicates = new dataSharePredicates.DataSharePredicates();
         let fetchOption = {
            fetchColumns: [],
            predicates: predicates
         };
         let fetchResult = await photoAccessHelper.getAssets(fetchOption);
         console.info('[picker] getThumbnail fetchResult: ' + fetchResult);
         const asset = await fetchResult.getFirstObject();
         console.info('[picker] getThumbnail asset displayName = ', asset.displayName);
         asset.getThumbnail().then((pixelMap) => {
            let pixelBytesNumber = pixelMap.getPixelBytesNumber();
            const readBuffer = new ArrayBuffer(pixelBytesNumber);
            pixelMap.readPixelsToBuffer(readBuffer).then(() => {
               pixelmapArrayBuffer = readBuffer;
            })
         }).catch((err) => {
            console.error('[picker] getThumbnail failed with error: ' + err);
         });
      } catch (error) {
         console.error('[picker] getThumbnail error = ' + error);
      }
   }
A
Annie_wang 已提交
54 55
   ```

A
Annie_wang 已提交
56
3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the image. After the user selects the destination folder, the image is saved and the URI of the saved image is returned.
A
Annie_wang 已提交
57
   
A
Annie_wang 已提交
58
   The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
A
Annie_wang 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

   ```ts  
   let uri:string;
   async photoViewPickerSave() {
      try {
         const photoSaveOptions = new picker.PhotoSaveOptions(); // Create a photoSaveOptions instance.
         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.

         const photoViewPicker = new picker.PhotoViewPicker();
         try {
            let photoSaveResult = await photoViewPicker.save(photoSaveOptions);
            if (photoSaveResult != undefined) {
               console.info("[picker] photoViewPickerSave photoSaveResult = " + JSON.stringify(photoSaveResult));
               this.uri = photoSaveResult[0];
               console.info('photoViewPicker.save to file succeed and uri is:' + photoSaveResult[0]);
            }
         } catch (err) {
            console.error(`[picker] Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
         }
      } catch (error) {
         console.info("[picker] photoViewPickerSave error = " + error);
      }
   }
A
Annie_wang 已提交
82 83
   ```

A
Annie_wang 已提交
84
4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
A
Annie_wang 已提交
85

A
Annie_wang 已提交
86
   Then, use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to modify the file based on the FD, and close the FD after the modification is complete.
A
Annie_wang 已提交
87 88

   ```ts
A
Annie_wang 已提交
89 90 91 92 93 94 95 96 97 98
   async writeOnly(uri) {
      try {
         let file = fs.openSync(uri, fs.OpenMode.WRITE_ONLY);
         let writeLen = await fs.write(file.fd, pixelmapArrayBuffer);
         fs.closeSync(file);
         console.info("[picker] writeOnly writeLen = " + writeLen);
      } catch (error) {
         console.info("[picker] writeOnly error: " + error);
      }
   }
A
Annie_wang 已提交
99 100 101 102
   ```

## Saving Documents

A
Annie_wang 已提交
103
1. Import the **picker** and **fs** modules.
A
Annie_wang 已提交
104 105 106

   ```ts
   import picker from '@ohos.file.picker';
A
Annie_wang 已提交
107
   import fs from '@ohos.file.fs';
A
Annie_wang 已提交
108 109 110 111 112 113
   ```

2. Create a **documentSaveOptions** instance.

   ```ts
   const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance.
A
Annie_wang 已提交
114
   documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the name of the document to save.
A
Annie_wang 已提交
115 116
   ```

A
Annie_wang 已提交
117
3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open 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.
A
Annie_wang 已提交
118
   
A
Annie_wang 已提交
119
   The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
A
Annie_wang 已提交
120 121

   ```ts
A
Annie_wang 已提交
122
   let uri = null;
A
Annie_wang 已提交
123
   const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
A
Annie_wang 已提交
124
   documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => {
A
Annie_wang 已提交
125 126
     uri = documentSaveResult[0];
     console.info('documentViewPicker.save to file succeed and uri is:' + uri);
A
Annie_wang 已提交
127 128 129 130 131
   }).catch((err) => {
     console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
   })
   ```

A
Annie_wang 已提交
132
4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
A
Annie_wang 已提交
133 134

   ```ts
A
Annie_wang 已提交
135
   let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
A
Annie_wang 已提交
136 137 138
   console.info('file fd: ' + file.fd);
   ```

A
Annie_wang 已提交
139
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the document based on the FD, and then close the FD.
A
Annie_wang 已提交
140 141 142 143 144

   ```ts
   let writeLen = fs.writeSync(file.fd, 'hello, world');
   console.info('write data to file succeed and size is:' + writeLen);
   fs.closeSync(file);
A
Annie_wang 已提交
145 146 147 148
   ```

## Saving Audio Files

A
Annie_wang 已提交
149
1. Import the **picker** and **fs** modules.
A
Annie_wang 已提交
150 151 152

   ```ts
   import picker from '@ohos.file.picker';
A
Annie_wang 已提交
153
   import fs from '@ohos.file.fs';
A
Annie_wang 已提交
154 155 156 157 158 159
   ```

2. Create an **audioSaveOptions** instance.

   ```ts
   const audioSaveOptions = new picker.AudioSaveOptions(); // Create an audioSaveOptions instance.
A
Annie_wang 已提交
160
   audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the name of the audio file to save.
A
Annie_wang 已提交
161 162
   ```

A
Annie_wang 已提交
163
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the file. After the user selects the destination folder, the audio file is saved and the URI of the file saved is returned.
A
Annie_wang 已提交
164
   
A
Annie_wang 已提交
165
   The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
A
Annie_wang 已提交
166
   
A
Annie_wang 已提交
167
   ```ts
A
Annie_wang 已提交
168
   let uri = null;
A
Annie_wang 已提交
169
   const audioViewPicker = new picker.AudioViewPicker();
A
Annie_wang 已提交
170
   audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => {
A
Annie_wang 已提交
171 172
     uri = audioSelectResult[0];
     console.info('audioViewPicker.save to file succeed and uri is:' + uri);
A
Annie_wang 已提交
173 174 175 176 177
   }).catch((err) => {
     console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
   })
   ```

A
Annie_wang 已提交
178
4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
A
Annie_wang 已提交
179 180

   ```ts
A
Annie_wang 已提交
181
   let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
A
Annie_wang 已提交
182 183 184
   console.info('file fd: ' + file.fd);
   ```

A
Annie_wang 已提交
185
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD.
A
Annie_wang 已提交
186 187 188 189 190

   ```ts
   let writeLen = fs.writeSync(file.fd, 'hello, world');
   console.info('write data to file succeed and size is:' + writeLen);
   fs.closeSync(file);
A
Annie_wang 已提交
191
   ```
A
Annie_wang 已提交
192