讨论广场 问答详情
OH5.0下载文件失败
代码论斤卖 2025-05-27 21:59:08
27 评论 分享

使用request.downloadFile接口下载文件,如下地址http://archive.spacemit.com/tools/openharmony/data/ohos.samples.flipclock/FlipClock-1.0.0.hap   返回404 ,实际浏览器直接打开可以下载,什么问题?

27 评论 分享
写回答
全部评论(2)

确认服务器是否拦截了非浏览器请求
curl -v -o output.hap http://archive.spacemit.com/tools/openharmony/data/ohos.samples.flipclock/FlipClock-1.0.0.hap

然后再尝试加上浏览器的请求头

curl -v -o output.hap \
  -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)" \
  -H "Referer: http://archive.spacemit.com" \
  http://archive.spacemit.com/tools/openharmony/data/ohos.samples.flipclock/FlipClock-1.0.0.hap

若加了 User-Agent 和 Referer 后可下载成功,那么问题就确定是请求头导致的。

2025-05-28 10:17:42

代码如下:

let filePath = globalThis.abilityContext.filesDir + '/' + this.appInfo.packageName + '-' + this.appInfo.version + ".hap";

// 判断文件是否存在
fs.access(filePath).then((res) => {
  if (res) {
    // 存在,直接安装
    this.installApp(filePath);
  } else {
    // 不存在,下载并安装
    try {
      console.info('fufufu Download task failed. Cause:' + this.appInfo.getHapUrl());
      console.info('fufufu Download task failed. Cause11:' + filePath);
      request.downloadFile(globalThis.abilityContext, {
        url: this.appInfo.getHapUrl(),
        filePath: filePath
      }).then((data) => {
        downloadTask = data;
        // 监听下载完成
        downloadTask.on('complete', function callback() {
          console.info('Download task completed.');
          // 安装应用
          _this.installApp(filePath);
        });
        // 监听下载失败
        downloadTask.on('fail', function callBack(err) {
          console.info('Download task failed. Cause:' + err);
          this.installLoading = false;
          promptAction.showToast({ message: '下载失败', duration: ToastDuration });
        });
      }).catch((err) => {
        console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
        this.installLoading = false;
        promptAction.showToast({ message: '下载失败', duration: ToastDuration });
      })
2025-05-27 22:23:14