• 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 { BusinessError, request } from '@kit.BasicServicesKit';
177let context = getContext(this) as common.UIAbilityContext;
178let filesDir = context.filesDir;
179
180let config: request.agent.Config = {
181  action: request.agent.Action.DOWNLOAD,
182  url: 'https://xxxx/test.txt',
183  saveas: 'xxxx.txt',
184  gauge: true,
185  overwrite: true,
186  network: request.agent.Network.WIFI,
187};
188request.agent.create(context, config).then((task: request.agent.Task) => {
189  task.start((err: BusinessError) => {
190    if (err) {
191      console.error(`Failed to start the download task, Code: ${err.code}  message: ${err.message}`);
192      return;
193    }
194  });
195  task.on('progress', async(progress) => {
196    console.warn(`/Request download status ${progress.state}, downloaded ${progress.processed}`);
197  })
198  task.on('completed', async() => {
199    console.warn(`/Request download completed`);
200    let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
201    let arrayBuffer = new ArrayBuffer(1024);
202    let readLen = fs.readSync(file.fd, arrayBuffer);
203    let buf = buffer.from(arrayBuffer, 0, readLen);
204    console.info(`The content of file: ${buf.toString()}`);
205    fs.closeSync(file);
206    // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object.
207    request.agent.remove(task.tid);
208  })
209}).catch((err: BusinessError) => {
210  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
211});
212```
213