• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.request.cacheDownload (Download and Cache)
2
3The **request** module provides applications with the basic capabilities of file upload and download and background transfer proxy.
4
5- The child component **cacheDownload** provides the basic capability of caching application resources in advance.
6
7- **cacheDownload** uses the HTTP protocol to download data and caches data resources to the application memory or files in the application sandbox directory.
8
9- The cached data can be used by some ArkUI components, such as the **Image** component, to improve resource loading efficiency. Check whether the ArkUI components support this function by referring to the ArkUI component topics.
10
11> **NOTE**
12>
13> The initial APIs of this module are supported since API version 18. Newly added APIs will be marked with a superscript to indicate their earliest API version.
14
15## Modules to Import
16
17```js
18import { cacheDownload } from '@kit.BasicServicesKit';
19```
20
21## cacheDownload.CacheDownloadOptions
22
23Provides configuration options for download and cache in terms of HTTP, transfer, and task.
24
25**System capability**: SystemCapability.Request.FileTransferAgent
26
27| Name     | Type                      | Mandatory| Description                   |
28|---------|--------------------------|----|-----------------------|
29| headers | Record\<string, string\> | No | Request header used by a download-and-cache task during HTTP transfer.|
30
31## cacheDownload.download
32
33download(url: string, options: CacheDownloadOptions)
34
35Downloads a task from a specified URL. If the transfer is successful, the data is downloaded to the memory cache and file cache.
36
37- After automatically decompressing during HTTP transfer, the size of the target resource cannot exceed 20971520 bytes (20 MB). Otherwise, the resource fails to store in the memory cache or file cache.
38
39- When caching the downloaded data, if the data already exists in the destination URL, the new data will overwrite the old one.
40
41- In addition, the system determines whether to store the target resource in a specified location based on each cache type's size limit in **cacheDownload**. By default, the LRU mode is used to replace the existing cached data.
42
43- This API uses a synchronous method and does not block the calling thread.
44
45**Required permissions**: ohos.permission.INTERNET
46
47**System capability**: SystemCapability.Request.FileTransferAgent
48
49**Parameters**
50
51| Name    | Type                                                        | Mandatory| Description                            |
52|---------|------------------------------------------------------------|----|--------------------------------|
53| url     | string                                                     | Yes | URL of the target resource. Only the HTTP protocol is supported. The URL length cannot exceed 8192 bytes.|
54| options | [CacheDownloadOptions](#cachedownloadcachedownloadoptions) | Yes | Cache download options for the target resource.                  |
55
56**Error codes**
57
58For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
59
60| ID   | Error Message                                                                                                                                     |
61|----------|-------------------------------------------------------------------------------------------------------------------------------------------|
62| 201      | permission denied.                                                                                                              |
63| 401      | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. |
64
65**Example**:
66
67  ```ts
68  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
69
70  // Provide configuration options for the download-and-cache task.
71  let options: cacheDownload.CacheDownloadOptions = {};
72
73  try {
74    // Download the resource. If the download is successful, the resource will be cached to the specified file in the application memory or sandbox directory.
75    cacheDownload.download("https://www.example.com", options);
76  } catch (err) {
77    console.error(`Failed to download the resource. err: ${JSON.stringify(err)}`);
78  }
79  ```
80
81## cacheDownload.cancel
82
83cancel(url: string)
84
85Cancels an ongoing download-and-cache task based on the URL. The saved memory cache and file cache are not affected.
86
87- If the task corresponding to the URL does not exist, no operation is required.
88
89- This API uses a synchronous method and does not block the calling thread.
90
91**System capability**: SystemCapability.Request.FileTransferAgent
92
93**Parameters**
94
95| Name | Type    | Mandatory| Description                            |
96|------|--------|----|--------------------------------|
97| url  | string | Yes | URL of the target resource. Only the HTTP protocol is supported. The URL length cannot exceed 8192 bytes.|
98
99**Error codes**
100
101For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
102
103| ID   | Error Message                                                                                                                                     |
104|----------|-------------------------------------------------------------------------------------------------------------------------------------------|
105| 401      | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. |
106
107**Example**:
108
109  ```ts
110  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
111
112  // Provide configuration options for the download-and-cache task.
113  let options: cacheDownload.CacheDownloadOptions = {};
114
115  try {
116    // Download the resource. If the download is successful, the resource will be cached to the specified file in the application memory or sandbox directory.
117    cacheDownload.download("https://www.example.com", options);
118  } catch (err) {
119    console.error(`Failed to download the resource. err: ${JSON.stringify(err)}`);
120  }
121
122  // Other service logic is omitted here.
123
124  try {
125    // Cancel the download-and-cache task when it is not required. The cached data is not affected.
126    cacheDownload.cancel("https://www.example.com");
127  } catch (err) {
128    console.error(`Failed to cancel the task. err: ${JSON.stringify(err)}`);
129  }
130  ```
131
132## cacheDownload.setMemoryCacheSize
133
134setMemoryCacheSize(bytes: number)
135
136Sets the upper limit of the memory cache size for the **cacheDownload** component.
137
138- When this API is used to adjust the cache size, the LRU mode is used by default to clear redundant cached data in the memory.
139
140- This API uses a synchronous method and does not block the calling thread.
141
142**System capability**: SystemCapability.Request.FileTransferAgent
143
144**Parameters**
145
146| Name  | Type    | Mandatory| Description                                     |
147|-------|--------|----|-----------------------------------------|
148| bytes | number | Yes | Upper limit of the cache. The default value is 0 bytes, and the maximum value cannot exceed 1073741824 bytes (1 GB).|
149
150**Error codes**
151
152For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
153
154| ID   | Error Message                                                                                                                                     |
155|----------|-------------------------------------------------------------------------------------------------------------------------------------------|
156| 401      | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. |
157
158**Example**:
159
160  ```ts
161  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
162
163  try {
164    // Set the upper limit of the memory cache size.
165    cacheDownload.setMemoryCacheSize(10 * 1024 * 1024);
166  } catch (err) {
167    console.error(`Failed to set memory cache size. err: ${JSON.stringify(err)}`);
168  }
169  ```
170
171## cacheDownload.setFileCacheSize
172
173setFileCacheSize(bytes: number)
174
175Sets the upper limit of the file cache size for the **cacheDownload** component.
176
177- When this API is used to adjust the cache size, the LRU mode is used by default to clear redundant cached data in the file.
178
179- This API uses a synchronous method and does not block the calling thread.
180
181**System capability**: SystemCapability.Request.FileTransferAgent
182
183**Parameters**
184
185| Name  | Type    | Mandatory| Description                                                        |
186|-------|--------|----|------------------------------------------------------------|
187| bytes | number | Yes | Upper limit of the cache. The default value is 104857600 bytes (100 MB), and the maximum value is 4294967296 bytes (4 GB).|
188
189**Error codes**
190
191For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
192
193| ID   | Error Message                                                                                                                                     |
194|----------|-------------------------------------------------------------------------------------------------------------------------------------------|
195| 401      | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. |
196
197**Example**:
198
199  ```ts
200  import { cacheDownload, BusinessError } from '@kit.BasicServicesKit';
201
202  try {
203    // Set the upper limit of the file cache size.
204    cacheDownload.setFileCacheSize(100 * 1024 * 1024);
205  } catch (err) {
206    console.error(`Failed to set file cache size. err: ${JSON.stringify(err)}`);
207  }
208  ```
209