• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Uploading and Downloading Application Files
2
3This topic describes how to upload an application file to a network server and download a network resource file from a network server to a local application file directory.
4
5## Uploading an Application File
6
7You can use **uploadFile()** in [ohos.request](../../reference/apis-basic-services-kit/js-apis-request.md) to upload local files. The system service agent uploads the files. In API version 12, you can set the address of the agent in **request.agent.create()**.
8
9> **NOTE**
10>
11> Currently, only the files in the **cache/** directory (specified by **cacheDir**) can be uploaded.
12>
13> To use **uploadFile()** in **ohos.request**, you need to [declare permissions](../../security/AccessToken/declare-permissions.md): ohos.permission.INTERNET.
14
15The following code demonstrates how to upload files from a cache directory of an application to a network server in two ways:
16
17```ts
18// Way 1: Use request.uploadFile.
19// pages/xxx.ets
20import { common } from '@kit.AbilityKit';
21import fs from '@ohos.file.fs';
22import { BusinessError, request } from '@kit.BasicServicesKit';
23
24// Obtain the application file path.
25let context = getContext(this) as common.UIAbilityContext;
26let cacheDir = context.cacheDir;
27
28// Create an application file locally.
29let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
30fs.writeSync(file.fd, 'upload file test');
31fs.closeSync(file);
32
33// Configure the upload task.
34let files: Array<request.File> = [
35// "internal://cache" in uri corresponds to the cacheDir directory.
36  { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
37]
38let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }];
39let uploadConfig: request.UploadConfig = {
40  url: 'https://xxx',
41  header: {
42    'key1':'value1',
43    'key2':'value2'
44  },
45  method: 'POST',
46  files: files,
47  data: data
48}
49
50// Upload the created application file to the network server.
51try {
52  request.uploadFile(context, uploadConfig)
53    .then((uploadTask: request.UploadTask) => {
54      uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
55        for (let i = 0; i < taskStates.length; i++) {
56          console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
57        }
58      });
59    })
60    .catch((err: BusinessError) => {
61      console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
62    })
63} catch (error) {
64  let err: BusinessError = error as BusinessError;
65  console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
66}
67```
68
69```ts
70// Way 2: Use request.agent.
71// pages/xxx.ets
72import { common } from '@kit.AbilityKit';
73import fs from '@ohos.file.fs';
74import { BusinessError, request } from '@kit.BasicServicesKit';
75// Obtain the application file path.
76let context = getContext(this) as common.UIAbilityContext;
77let cacheDir = context.cacheDir;
78
79// Create an application file locally.
80let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
81fs.writeSync(file.fd, 'upload file test');
82fs.closeSync(file);
83let attachments: Array<request.agent.FormItem> = [{
84  name: "test",
85  value: [
86    {
87      filename: "test.txt",
88      path: "./test.txt",
89    },
90  ]
91}];
92let config: request.agent.Config = {
93  action: request.agent.Action.UPLOAD,
94  url: 'http://xxx',
95  mode: request.agent.Mode.FOREGROUND,
96  overwrite: true,
97  method: "POST",
98  headers: {
99    'key1':'value1',
100    'key2':'value2'
101  },
102  data: attachments,
103  saveas: "./"
104};
105request.agent.create(getContext(), config).then((task: request.agent.Task) => {
106  task.start((err: BusinessError) => {
107    if (err) {
108      console.error(`Failed to start the upload task, Code: ${err.code}  message: ${err.message}`);
109      return;
110    }
111  });
112  task.on('progress', async(progress) => {
113    console.warn(`/Request upload status ${progress.state}, uploaded ${progress.processed}`);
114  })
115  task.on('completed', async() => {
116    console.warn(`/Request upload completed`);
117    // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object.
118    request.agent.remove(task.tid);
119  })
120}).catch((err: BusinessError) => {
121  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
122});
123```
124
125## Downloading a Network Resource File to an Application Directory
126
127You can use **downloadFile()** in [ohos.request](../../reference/apis-basic-services-kit/js-apis-request.md) to download network resource files to a local application directory. You can use the [ohos.file.fs](../../reference/apis-core-file-kit/js-apis-file-fs.md) APIs to access the downloaded files. For details, see [Accessing Application Files](../../file-management/app-file-access.md). The system service agent downloads the files. In API version 12, you can set the address of the agent in **request.agent.create()**.
128
129> **NOTE**
130>
131> Currently, network resource files can be downloaded only to the application file directory.
132>
133> To use **uploadFile()** in **ohos.request**, you need to [declare permissions](../../security/AccessToken/declare-permissions.md): ohos.permission.INTERNET.
134
135The following code demonstrates how to download files from a network server to an application directory in two ways:
136
137```ts
138// Way 1: Use request.downloadFile.
139// pages/xxx.ets
140// Download the network resource file to the local application file directory, and read data from the file.
141import { common } from '@kit.AbilityKit';
142import fs from '@ohos.file.fs';
143import { BusinessError, request } from '@kit.BasicServicesKit';
144import { buffer } from '@kit.ArkTS';
145
146// Obtain the application file path.
147let context = getContext(this) as common.UIAbilityContext;
148let filesDir = context.filesDir;
149
150try {
151  request.downloadFile(context, {
152    url: 'https://xxxx/xxxx.txt',
153    filePath: filesDir + '/xxxx.txt'
154  }).then((downloadTask: request.DownloadTask) => {
155    downloadTask.on('complete', () => {
156      console.info('download complete');
157      let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
158      let arrayBuffer = new ArrayBuffer(1024);
159      let readLen = fs.readSync(file.fd, arrayBuffer);
160      let buf = buffer.from(arrayBuffer, 0, readLen);
161      console.info(`The content of file: ${buf.toString()}`);
162      fs.closeSync(file);
163    })
164  }).catch((err: BusinessError) => {
165    console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
166  });
167} catch (error) {
168  let err: BusinessError = error as BusinessError;
169  console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
170}
171```
172```ts
173// Way 2: Use request.agent.
174// pages/xxx.ets
175// Download the network resource file to the local application file directory, and read data from the file.
176import { common } from '@kit.AbilityKit';
177import fs from '@ohos.file.fs';
178import { BusinessError, request } from '@kit.BasicServicesKit';
179import { buffer } from '@kit.ArkTS';
180
181// Obtain the application file path.
182let context = getContext(this) as common.UIAbilityContext;
183let filesDir = context.filesDir;
184
185let config: request.agent.Config = {
186  action: request.agent.Action.DOWNLOAD,
187  url: 'https://xxxx/test.txt',
188  saveas: 'xxxx.txt',
189  gauge: true,
190  overwrite: true,
191  network: request.agent.Network.WIFI,
192};
193request.agent.create(context, config).then((task: request.agent.Task) => {
194  task.start((err: BusinessError) => {
195    if (err) {
196      console.error(`Failed to start the download task, Code: ${err.code}  message: ${err.message}`);
197      return;
198    }
199  });
200  task.on('progress', async(progress) => {
201    console.warn(`/Request download status ${progress.state}, downloaded ${progress.processed}`);
202  })
203  task.on('completed', async() => {
204    console.warn(`/Request download completed`);
205    let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
206    let arrayBuffer = new ArrayBuffer(1024);
207    let readLen = fs.readSync(file.fd, arrayBuffer);
208    let buf = buffer.from(arrayBuffer, 0, readLen);
209    console.info(`The content of file: ${buf.toString()}`);
210    fs.closeSync(file);
211    // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object.
212    request.agent.remove(task.tid);
213  })
214}).catch((err: BusinessError) => {
215  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
216});
217```
218
219## Adding Network Configuration
220
221### Intercepting HTTP
222
223You can set the configuration file to intercept HTTP. After HTTP is disabled for the upload and download module, upload and download tasks using plaintext HTTP cannot be created. The configuration file is stored in the **src/main/resources/base/profile/network_config.json** directory of the application.
224
225The sample configuration file is as follows:
226
227```ts
228{
229  "network-security-config": {
230    "base-config": {
231      "cleartextTrafficPermitted": true,
232      "trust-anchors": [
233        {
234          "certificates": "/etc/security/certificates"
235        }
236      ]
237    },
238    "domain-config": [
239      {
240        "cleartextTrafficPermitted": true,
241        "domains": [
242          {
243            "include-subdomains": true,
244            "name": "*.example.com"
245          }
246        ],
247      }
248    ]
249  }
250}
251
252```
253
254The table below lists the description of each field.
255
256| Field                     | Type           | Description                                  |
257| --------------------------| --------------- | -------------------------------------- |
258| base-config:<br> cleartextTrafficPermitted | boolean | Whether plaintext transfer is allowed in the global configuration. The value **true** means that plaintext transfer is allowed, that is, HTTP is not intercepted, and **false** means the opposite.|
259| domain-config:<br> cleartextTrafficPermitted | boolean | Whether plaintext transfer is allowed in a specified domain. The value **true** means that plaintext transfer is allowed, that is, HTTP is not intercepted, and **false** means the opposite.|
260| include-subdomains | boolean | Whether a rule applies to subdomains. The value **true** means that the regular expression is used to match the domain name, and **false** means the opposite.|
261