• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Updating Local and Online Images in the Widget
2
3
4Typically, a widget includes local images or online images downloaded from the network. To obtain local and online images, use the FormExtensionAbility. The following exemplifies how to show local and online images on a widget.
5
6
71. For the widget to download online images, declare the **ohos.permission.INTERNET** permission for the widget. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md).
8
92. Update local files in the **onAddForm** lifecycle callback of the EntryFormAbility.
10
11    ```ts
12    import { Want } from '@kit.AbilityKit';
13    import { BusinessError } from '@kit.BasicServicesKit';
14    import { fileIo } from '@kit.CoreFileKit';
15    import { formBindingData, FormExtensionAbility } from '@kit.FormKit';
16    import { hilog } from '@kit.PerformanceAnalysisKit';
17
18    const TAG: string = 'WgtImgUpdateEntryFormAbility';
19    const DOMAIN_NUMBER: number = 0xFF00;
20
21    export default class WgtImgUpdateEntryFormAbility extends FormExtensionAbility {
22      // When the widget is added, a local image is opened and transferred to the widget page for display.
23      onAddForm(want: Want): formBindingData.FormBindingData {
24        // Assume that the local image head.PNG is in the tmp directory of the current widget.
25        let tempDir = this.context.getApplicationContext().tempDir;
26        hilog.info(DOMAIN_NUMBER, TAG, `tempDir: ${tempDir}`);
27        let imgMap: Record<string, number> = {};
28        try {
29          // Open the local image and obtain the FD after the image is opened.
30          let file = fileIo.openSync(tempDir + '/' + 'head.PNG');
31          imgMap['imgBear'] = file.fd;
32        } catch (e) {
33          hilog.error(DOMAIN_NUMBER, TAG, `openSync failed: ${JSON.stringify(e as BusinessError)}`);
34        }
35
36        class FormDataClass {
37          text: string = 'Image: Bear';
38          loaded: boolean = true;
39          // If an image needs to be displayed in the widget, the value of imgName must be the same as the key 'imgBear' in formImages.
40          imgName: string = 'imgBear';
41          // If an image needs to be displayed in the widget, the formImages field is mandatory (formImages cannot be left blank or renamed), and 'imgBear' corresponds to the FD.
42          formImages: Record<string, number> = imgMap;
43        }
44
45        let formData = new FormDataClass();
46        // Encapsulate the FD in formData and return it to the widget page.
47        return formBindingData.createFormBindingData(formData);
48      }
49      //...
50    }
51    ```
52
533. Update online files in the **onFormEvent** lifecycle callback of the EntryFormAbility.
54
55      ```ts
56      import { BusinessError } from '@kit.BasicServicesKit';
57      import { fileIo } from '@kit.CoreFileKit';
58      import { formBindingData, FormExtensionAbility, formProvider } from '@kit.FormKit';
59      import { http } from '@kit.NetworkKit';
60      import { hilog } from '@kit.PerformanceAnalysisKit';
61
62      const TAG: string = 'WgtImgUpdateEntryFormAbility';
63      const DOMAIN_NUMBER: number = 0xFF00;
64
65      export default class WgtImgUpdateEntryFormAbility extends FormExtensionAbility {
66        async onFormEvent(formId: string, message: string): Promise<void> {
67          let param: Record<string, string> = {
68            'text': 'Updating...'
69          };
70          let formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(param);
71          formProvider.updateForm(formId, formInfo);
72
73          // Note: After being started with the triggering of the lifecycle callback, the FormExtensionAbility can run in the background for only 5 seconds.
74          // When possible, limit the size of the image to download. If an image cannot be downloaded within 5 seconds, it will not be updated to the widget page.
75          let netFile = 'https://cn-assets.gitee.com/assets/mini_app-e5eee5a21c552b69ae6bf2cf87406b59.jpg'; // Specify the URL of the image to download.
76          let tempDir = this.context.getApplicationContext().tempDir;
77          let fileName = 'file' + Date.now();
78          let tmpFile = tempDir + '/' + fileName;
79          let imgMap: Record<string, number> = {};
80
81          class FormDataClass {
82            text: string = 'Image: Bear' + fileName;
83            loaded: boolean = true;
84            // If an image needs to be displayed in the widget, the value of imgName must be the same as the key fileName in formImages.
85            imgName: string = fileName;
86            // If an image needs to be displayed in the widget, the formImages field is mandatory (formImages cannot be left blank or renamed), and fileName corresponds to the FD.
87            formImages: Record<string, number> = imgMap;
88          }
89
90          let httpRequest = http.createHttp()
91          let data = await httpRequest.request(netFile);
92          if (data?.responseCode == http.ResponseCode.OK) {
93            try {
94              let imgFile = fileIo.openSync(tmpFile, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
95              imgMap[fileName] = imgFile.fd;
96              try{
97                let writeLen: number = await fileIo.write(imgFile.fd, data.result as ArrayBuffer);
98                hilog.info(DOMAIN_NUMBER, TAG, "write data to file succeed and size is:" + writeLen);
99                hilog.info(DOMAIN_NUMBER, TAG, 'ArkTSCard download complete: %{public}s', tmpFile);
100                try {
101                  let formData = new FormDataClass();
102                  let formInfo = formBindingData.createFormBindingData(formData);
103                  await formProvider.updateForm(formId, formInfo);
104                  hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'FormAbility updateForm success.');
105                } catch (error) {
106                  hilog.error(DOMAIN_NUMBER, TAG, `FormAbility updateForm failed: ${JSON.stringify(error)}`);
107                }
108              } catch (err) {
109                hilog.error(DOMAIN_NUMBER, TAG, "write data to file failed with error message: " + err.message + ", error code: " + err.code);
110              } finally {
111                // Before executing fileIo.closeSync, ensure that formProvider.updateForm has been executed.
112                fileIo.closeSync(imgFile);
113              };
114            } catch (e) {
115              hilog.error(DOMAIN_NUMBER, TAG, `openSync failed: ${JSON.stringify(e as BusinessError)}`);
116            }
117
118          } else {
119            hilog.error(DOMAIN_NUMBER, TAG, `ArkTSCard download task failed`);
120            let param: Record<string, string> = {
121              'text': 'Update failed.'
122            };
123            let formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(param);
124            formProvider.updateForm(formId, formInfo);
125          }
126          httpRequest.destroy();
127        }
128      }
129      ```
130
1314. On the widget page, use the **backgroundImage** attribute to display the widget content passed from the EntryFormAbility.
132
133    ```ts
134    let storageWidgetImageUpdate = new LocalStorage();
135
136    @Entry(storageWidgetImageUpdate)
137    @Component
138    struct WidgetImageUpdateCard {
139      @LocalStorageProp('text') text: ResourceStr = $r('app.string.loading');
140      @LocalStorageProp('loaded') loaded: boolean = false;
141      @LocalStorageProp('imgName') imgName: ResourceStr = $r('app.string.imgName');
142
143      build() {
144        Column() {
145          Column() {
146            Text(this.text)
147              .fontColor('#FFFFFF')
148              .opacity(0.9)
149              .fontSize(12)
150              .textOverflow({ overflow: TextOverflow.Ellipsis })
151              .maxLines(1)
152              .margin({ top: '8%', left: '10%' })
153          }.width('100%').height('50%')
154          .alignItems(HorizontalAlign.Start)
155
156          Row() {
157            Button() {
158              Text($r('app.string.update'))
159                .fontColor('#45A6F4')
160                .fontSize(12)
161            }
162            .width(120)
163            .height(32)
164            .margin({ top: '30%', bottom: '10%' })
165            .backgroundColor('#FFFFFF')
166            .borderRadius(16)
167            .onClick(() => {
168              postCardAction(this, {
169                action: 'message',
170                params: {
171                  info: 'refreshImage'
172                }
173              });
174            })
175          }.width('100%').height('40%')
176          .justifyContent(FlexAlign.Center)
177        }
178        .width('100%').height('100%')
179        .backgroundImage(this.loaded ? 'memory://' + this.imgName : $r('app.media.ImageDisp'))
180        .backgroundImageSize(ImageSize.Cover)
181      }
182    }
183    ```
184
185> **NOTE**
186>
187> - The **Image** component displays images in the remote memory based on the (**memory://**) identifier in the input parameter (**memory://fileName**). The value of **fileName** must be consistent with the key in the object (**'formImages': {key: fd}**) passed by the EntryFormAbility.
188>
189> - The **Image** component determines whether to update the image by comparing the values of **imgName** consecutively passed by the EntryFormAbility. It updates the image only when the values are different.
190>
191> - The size of the image displayed on the widget must be less than 2 MB.
192