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 header = new Map<Object, string>(); 35header.set('key1', 'value1'); 36header.set('key2', 'value2'); 37let files: Array<request.File> = [ 38// "internal://cache" in uri corresponds to the cacheDir directory. 39 { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } 40] 41let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }]; 42let uploadConfig: request.UploadConfig = { 43 url: 'https://xxx', 44 header: header, 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 data: attachments, 99 saveas: "./" 100}; 101request.agent.create(getContext(), config).then((task: request.agent.Task) => { 102 task.start((err: BusinessError) => { 103 if (err) { 104 console.error(`Failed to start the upload task, Code: ${err.code} message: ${err.message}`); 105 return; 106 } 107 }); 108 task.on('progress', async(progress) => { 109 console.warn(`/Request upload status ${progress.state}, uploaded ${progress.processed}`); 110 }) 111 task.on('completed', async() => { 112 console.warn(`/Request upload completed`); 113 }) 114}).catch((err: BusinessError) => { 115 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 116}); 117``` 118 119## Downloading a Network Resource File to an Application Directory 120 121You 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()**. 122 123> **NOTE** 124> 125> Currently, network resource files can be downloaded only to the application file directory. 126> 127> To use **uploadFile()** in **ohos.request**, you need to [declare permissions](../../security/AccessToken/declare-permissions.md): ohos.permission.INTERNET. 128 129The following code demonstrates how to download files from a network server to an application directory in two ways: 130 131```ts 132// Way 1: Use request.downloadFile. 133// pages/xxx.ets 134// Download the network resource file to the local application file directory, and read data from the file. 135import { common } from '@kit.AbilityKit'; 136import fs from '@ohos.file.fs'; 137import { BusinessError, request } from '@kit.BasicServicesKit'; 138import { buffer } from '@kit.ArkTS'; 139 140// Obtain the application file path. 141let context = getContext(this) as common.UIAbilityContext; 142let filesDir = context.filesDir; 143 144try { 145 request.downloadFile(context, { 146 url: 'https://xxxx/xxxx.txt', 147 filePath: filesDir + '/xxxx.txt' 148 }).then((downloadTask: request.DownloadTask) => { 149 downloadTask.on('complete', () => { 150 console.info('download complete'); 151 let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); 152 let arrayBuffer = new ArrayBuffer(1024); 153 let readLen = fs.readSync(file.fd, arrayBuffer); 154 let buf = buffer.from(arrayBuffer, 0, readLen); 155 console.info(`The content of file: ${buf.toString()}`); 156 fs.closeSync(file); 157 }) 158 }).catch((err: BusinessError) => { 159 console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`); 160 }); 161} catch (error) { 162 let err: BusinessError = error as BusinessError; 163 console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`); 164} 165``` 166```ts 167// Way 2: Use request.agent. 168// pages/xxx.ets 169// Download the network resource file to the local application file directory, and read data from the file. 170import { BusinessError, request } from '@kit.BasicServicesKit'; 171 172let config: request.agent.Config = { 173 action: request.agent.Action.DOWNLOAD, 174 url: 'https://xxxx/test.txt', 175 gauge: true, 176 overwrite: true, 177 network: request.agent.Network.WIFI, 178}; 179request.agent.create(getContext(), config).then((task: request.agent.Task) => { 180 task.start((err: BusinessError) => { 181 if (err) { 182 console.error(`Failed to start the upload task, Code: ${err.code} message: ${err.message}`); 183 return; 184 } 185 }); 186 task.on('progress', async(progress) => { 187 console.warn(`/Request download status ${progress.state}, downloaded ${progress.processed}`); 188 }) 189 task.on('completed', async() => { 190 console.warn(`/Request download completed`); 191 }) 192}).catch((err: BusinessError) => { 193 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 194}); 195``` 196