下载文件建议使用request.downloadFile方法,参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/app-file-upload-download-V5\#下载网络资源文件至应用文件目录参考示例:import request from '@ohos.request'; import { BusinessError } from '@ohos.base'; import fs, { ReadOptions } from '@ohos.file.fs'; import { buffer } from '@kit.ArkTS'; @Entry @Component export struct Index1 { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) Button('下载') .onClick(async () => { try { await request.downloadFile(getContext(), { url: 'http://testxxxxx.doc', filePath: getContext().filesDir + '/636444715e7d49ef810ce8aeb7444b9f.doc' }).then((downloadTask: request.DownloadTask) => { downloadTask.on('complete', () => { console.info('download complete'); let file = fs.openSync(getContext().filesDir + '/636444715e7d49ef810ce8aeb7444b9f.doc', fs.OpenMode.READ_WRITE); 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()}`); fs.closeSync(file); }) }).catch((err: BusinessError) => { console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`); }); } catch (error) { let err: BusinessError = error as BusinessError; console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`); } }) .width('100%') } .height('100%') } } }
下载文件建议使用request.downloadFile方法,参考文档:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/app-file-upload-download-V5\#下载网络资源文件至应用文件目录
参考示例: