Axios下载文件示例

2024-06-19 20:26:56 浏览数 (1)

Axios下载文件示例

设置下载路径filePath(默认在'internal://cache/'路径下)。

关于filePath filePath:'workspace/test.txt':默认路径下创建workspace路径,并将文件存储在workspace路径下。 filePath:'test.txt':将文件存储在默认路径下。 filePath:'workspace/':默认路径下创建workspace路径,并将文件存储在workspace路径下。

完整源码

代码语言:javascript复制
import axios, { AxiosError, AxiosProgressEvent, AxiosResponse } from '@ohos/axios';
import { promptAction } from '@kit.ArkUI';
import fs from '@ohos.file.fs';

@Entry
@Component
struct SecondPage {
  @State message: string = 'Hello World';
  @State downloadProgress: number = 0
  @State status: string | number = ''
  @State startTime: number = 0;
  @State endTime: number = 0;

  aboutToAppear(): void {

    this.downLoadFile()
  }


  downLoadFile() {
    this.startTime = new Date().getTime();
    let filePath = getContext(this).cacheDir   '/git.pdf'
    // 下载。如果文件已存在,则先删除文件。
    try {
      fs.accessSync(filePath);
      fs.unlinkSync(filePath);
    } catch (err) {
    }

    axios({
      url: 'https://www.gjtool.cn/pdfh5/git.pdf',
      method: 'get',
      context: getContext(this),
      filePath: filePath,
      onDownloadProgress: (progressEvent: AxiosProgressEvent): void => {
        promptAction.showToast({
          message: "下载进度"
        })

        this.message = JSON.stringify(progressEvent.progress)
        console.info("hhhhhhhh"   JSON.stringify(progressEvent))
        this.downloadProgress = progressEvent && progressEvent.loaded && progressEvent.total ?
        Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0;
        // console.info("progress: "   progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0)
      }
    }).then((res: AxiosResponse<string>) => {
      this.status = res ? res.status : '';
      this.message = res ? JSON.stringify(res.data) : '';
      this.endTime = new Date().getTime();
    }).catch((err: AxiosError) => {
      this.status = '';
      this.message = err.message;
      this.endTime = new Date().getTime();
    })
  }

  build() {
    Column() {
      Text(this.message)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)

      Progress({ value: this.downloadProgress, type: ProgressType.Linear })
        .color('#009BE8').width('100%')
        .margin({ top: 8, right: 10 })
        .style({ strokeWidth: 10 })
    }
    .height('100%')
    .width('100%')
  }
}

参考

axios[1]

参考资料

[1]

axios: https://gitee.com/openharmony-sig/ohos_axios#axios

0 人点赞