app-file-upload-download.md 4.7 KB
Newer Older
A
Annie_wang 已提交
1 2
# Uploading and Downloading an Application File

A
Annie_wang 已提交
3
This topic describes how to enable an application to upload an application file to a network server and download a network resource file from a network server to a local application directory.
A
Annie_wang 已提交
4 5 6 7 8 9 10 11 12

## Uploading an Application File

You can use [ohos.request](../reference/apis/js-apis-request.md) **uploadFile()** to upload local files. The system service proxy implements the upload.

> **NOTE**
>
> Currently, only the files in the **cache/** directories (**cacheDir**) can be uploaded.
>
A
Annie_wang 已提交
13
> 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).
A
Annie_wang 已提交
14 15 16 17 18 19 20 21

The following example demonstrates how to upload a file in the **cache** directory of an application to a network server.

```ts
// pages/xxx.ets
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
A
Annie_wang 已提交
22
import { BusinessError } from '@ohos.base';
A
Annie_wang 已提交
23 24 25 26 27 28 29 30 31 32 33

// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let cacheDir = context.cacheDir;

// Create an application file locally.
let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
fs.writeSync(file.fd, 'upload file test');
fs.closeSync(file);

// Configure the upload task.
A
Annie_wang 已提交
34 35 36 37 38 39 40 41
let header = new Map<Object, string>();
header.set('key1', 'value1');
header.set('key2', 'value2');
let files: Array<request.File> = [
  { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
]
let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }];
let uploadConfig: request.UploadConfig = {
A
Annie_wang 已提交
42
  url: 'https://xxx',
A
Annie_wang 已提交
43
  header: header,
A
Annie_wang 已提交
44
  method: 'POST',
A
Annie_wang 已提交
45 46
  files: files,
  data: data
A
Annie_wang 已提交
47 48 49 50 51
}

// Upload the created application file to the network server.
try {
  request.uploadFile(context, uploadConfig)
A
Annie_wang 已提交
52 53
    .then((uploadTask: request.UploadTask) => {
      uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
A
Annie_wang 已提交
54
        for (let i = 0; i < taskStates.length; i++) {
A
Annie_wang 已提交
55
          console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
A
Annie_wang 已提交
56 57 58
        }
      });
    })
A
Annie_wang 已提交
59
    .catch((err: BusinessError) => {
A
Annie_wang 已提交
60 61
      console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
    })
A
Annie_wang 已提交
62 63
} catch (error) {
  let err: BusinessError = error as BusinessError;
A
Annie_wang 已提交
64 65 66 67 68 69
  console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
}
```

## Downloading a Network Resource File to the Application File Directory

A
Annie_wang 已提交
70
You 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 in the same way as [accessing application files](app-file-access.md). The system service proxy implements the download.
A
Annie_wang 已提交
71 72 73 74 75

> **NOTE**
>
> Currently, network resource files can be downloaded only to an application file directory.
>
A
Annie_wang 已提交
76
> 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).
A
Annie_wang 已提交
77 78 79 80 81 82 83 84 85

The following example demonstrates how to download a network resource file to a local application file directory.

```ts
// pages/xxx.ets
// Download the network resource file to the local application file directory, and read data from the file.
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
A
Annie_wang 已提交
86 87
import { BusinessError } from '@ohos.base';
import buffer from '@ohos.buffer';
A
Annie_wang 已提交
88 89 90 91 92 93 94 95 96

// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;

try {
  request.downloadFile(context, {
    url: 'https://xxxx/xxxx.txt',
    filePath: filesDir + '/xxxx.txt'
A
Annie_wang 已提交
97
  }).then((downloadTask: request.DownloadTask) => {
A
Annie_wang 已提交
98 99 100
    downloadTask.on('complete', () => {
      console.info('download complete');
      let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
A
Annie_wang 已提交
101 102 103 104
      let arrayBuffer = new ArrayBuffer(1024);
      let readLen = fs.readSync(file.fd, arrayBuffer);
      let buf = buffer.from(arrayBuffer, 0, readLen);
      console.info(`The content of file: ${buf.toString()}`);
A
Annie_wang 已提交
105 106
      fs.closeSync(file);
    })
A
Annie_wang 已提交
107
  }).catch((err: BusinessError) => {
A
Annie_wang 已提交
108 109
    console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
  });
A
Annie_wang 已提交
110 111
} catch (error) {
  let err: BusinessError = error as BusinessError;
A
Annie_wang 已提交
112 113 114
  console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
}
```