HarmonyOS 使用http下载文件异常?

使用http.createHttp().request方法下载文件,word和pdf下载异常,excel和ppt可以下载,将word和pdf的下载地址拷贝到浏览器上均可下载。

阅读 484
1 个回答

下载文件建议使用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%')
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏