HarmonyOS 文件下载回调无响应?

代码如下:

import { request, BusinessError } from '@kit.BasicServicesKit'
import { common } from '@kit.AbilityKit';

const TAG = 'TextInputExample'

@Entry
@Component
struct TextInputExample {
  @State imgScr: string | ResourceStr = $r('app.media.adErr')
  private filePath: string = ''

  /**
   * 获取资源下载路径
   * @param context
   * @param url 下载地址
   * @param isTemp 是否临时路径
   * @returns
   */
  getResourcePath(context: Context, url: string, isTemp: boolean): string {
    let filePath = ''
    if (url) {
      let urlMD5 = 'xxx' // 此处使用string代替MD5加密
      let dirPath = context.cacheDir
      let suffix = url.slice(url.lastIndexOf('.')).toLowerCase()
      if (urlMD5 && dirPath) {
        if (isTemp) {
          filePath = dirPath + '/' + urlMD5 + '_tmp' + suffix
        } else {
          filePath = dirPath + '/' + urlMD5 + suffix
        }
      }
    }
    return filePath
  }

  /**
   * 下载资源
   * @param context
   * @param url
   * @param filePath
   * @param callback
   */
  downloadResource(context: Context, url: string, filePath: string, onSuccess?: (filePath: string) => void,
    onFailure?: (code: number, msg: string) => void) {
    try {
      request.downloadFile(context, {
        url: url,
        filePath: filePath
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('complete', () => {
          onSuccess?.(filePath)
        })
        downloadTask.off('fail', (code) => {
          console.debug(TAG, 'downloadResource', `Invoke downloadTask failed, code is ${code}`)
          onFailure?.(code, '')
        })
      })
    } catch (err) {
      console.debug(TAG, 'downloadResource',
        `Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      let e: BusinessError = err as BusinessError
      onFailure?.(e.code, e.message)
    }
  }

  aboutToAppear(): void {
    let context = getContext(this) as common.UIAbilityContext
    let url = 'https://xxx'
    this.filePath = this.getResourcePath(context, url, false)
    this.downloadResource(context, url, this.filePath)
  }

  build() {
    Column() {
      Row() {
        Image(this.imgScr)
          .width('100%')
          .onComplete((event) => {
            if (event?.loadingStatus === 1) {
              console.log('图片2加载成功', event?.loadingStatus)
            }
          })
          .onError(() => {
            console.log('图片2加载失败')
            this.imgScr = 'https://xxx'
          })
      }
      .width('50%')
      .height(300)
      .border({ width: 1, color: Color.Red })
    }
  }
}
阅读 569
1 个回答
downloadTask.off('fail', (code) => {
  console.debug(TAG, 'downloadResource', `Invoke downloadTask failed, code is ${code}`)
  onFailure?.(code, '')
})

上面的代码写错了,off是取消订阅事件,所以才不会进失败回调,参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5\#offcomplete–fail9

应该改为:

downloadTask.on('fail', (code) => {
  console.debug(TAG, 'downloadResource', `Invoke downloadTask failed, code is ${code}`)
  onFailure?.(code, '')
})

即可监听下载任务成功和失败事件。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进