• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Uploading and Downloading an Application File
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 directory.
4
5## Uploading an Application File
6
7You can use [ohos.request](../reference/apis/js-apis-request.md) **uploadFile()** to upload local files. The system service proxy implements the upload.
8
9> **NOTE**
10>
11> Currently, only the files in the **cache/** directories (**cacheDir**) can be uploaded.
12>
13> <br>The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
14
15The following example demonstrates how to upload a file in the **cache** directory of an application to a network server.
16
17```ts
18// pages/xxx.ets
19import common from '@ohos.app.ability.common';
20import fs from '@ohos.file.fs';
21import request from '@ohos.request';
22
23// Obtain the application file path.
24let context = getContext(this) as common.UIAbilityContext;
25let cacheDir = context.cacheDir;
26
27// Create an application file locally.
28let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
29fs.writeSync(file.fd, 'upload file test');
30fs.closeSync(file);
31
32// Configure the upload task.
33let uploadConfig = {
34  url: 'https://xxx',
35  header: { key1: 'value1', key2: 'value2' },
36  method: 'POST',
37  files: [
38    { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
39  ],
40  data: [
41    { name: 'name', value: 'value' }
42  ]
43}
44
45// Upload the created application file to the network server.
46try {
47  request.uploadFile(context, uploadConfig)
48    .then((uploadTask) => {
49      uploadTask.on('complete', (taskStates) => {
50        for (let i = 0; i < taskStates.length; i++) {
51          console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}');
52        }
53      });
54    })
55    .catch((err) => {
56      console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
57    })
58} catch (err) {
59  console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
60}
61```
62
63## Downloading a Network Resource File to the Application File Directory
64
65You can use [ohos.request](../reference/apis/js-apis-request.md) **downloadFile()** to download network resource files to a local application directory. You can use the ([ohos.file.fs](../reference/apis/js-apis-file-fs.md) APIs to access the downloaded files. For details, see [Accessing Application Files](app-file-access.md). The system service proxy implements the download.
66
67> **NOTE**
68>
69> Currently, network resource files can be downloaded only to an application file directory.
70>
71> <br>The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
72
73The following example demonstrates how to download a network resource file to a local application file directory.
74
75```ts
76// pages/xxx.ets
77// Download the network resource file to the local application file directory, and read data from the file.
78import common from '@ohos.app.ability.common';
79import fs from '@ohos.file.fs';
80import request from '@ohos.request';
81
82// Obtain the application file path.
83let context = getContext(this) as common.UIAbilityContext;
84let filesDir = context.filesDir;
85
86try {
87  request.downloadFile(context, {
88    url: 'https://xxxx/xxxx.txt',
89    filePath: filesDir + '/xxxx.txt'
90  }).then((downloadTask) => {
91    downloadTask.on('complete', () => {
92      console.info('download complete');
93      let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
94      let buf = new ArrayBuffer(1024);
95      let readLen = fs.readSync(file.fd, buf);
96      console.info(`The content of file: ${String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))}`);
97      fs.closeSync(file);
98    })
99  }).catch((err) => {
100    console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
101  });
102} catch (err) {
103  console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
104}
105```
106