下载HarmonyOS 鸿蒙Next资源文件

发布于 1周前 作者 phonegap100 来自 鸿蒙OS

下载HarmonyOS 鸿蒙Next资源文件

分别测试两个url:
http://vjs.zencdn.net/v/oceans.mp4【可以下载成功】
https://yfd-aries-online.fbcontent.cn/resource/1708329107553_md5_eecfd52597fb7ebe17f93d2b3a83f30c.zip
【一直报错:Incorrect parameter type】

const url_splits = url.split('/')
if (url_splits.length == 0) return
const file_name = url_splits.pop()
let context: common.ApplicationContext | undefined = AppStorage.get(AppStorageKey.APP_CONTEXT)
context = context?.getApplicationContext()
if (context == undefined || file_name == undefined) return
const unzipPath = context.cacheDir + '/unzip/'
const isExist = await fs.access(unzipPath)
if (!isExist) {
  await fs.mkdir(unzipPath)
}
const filePath =  unzipPath + file_name
const isFileExist = await fs.access(filePath)
if (isFileExist) {
  await fs.unlink(filePath)
}

try {
  const downloadTask = await request.downloadFile(context, {
    url: url,
    filePath: filePath,
  })
  downloadTask.on("progress", (receivedSize: number, totalSize: number) => {
    console.log(`index: ${index} receivedSize: ${receivedSize}  totalSize: ${totalSize}`);
  })

  downloadTask.on('complete', () => {
    ToastUtil.showToast('下载完成')
    console.log('index: $${index} complete');
  })

  downloadTask.on('fail', (err: number) => {
    console.log(`index: ${index} fail: ${err}`);
    ToastUtil.showToast(`下载失败: ${err}`)
  })
} catch (error) {
  ToastUtil.showToast((error as Error).message)
  console.log(error);
}

更多关于下载HarmonyOS 鸿蒙Next资源文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

8 回复

进过多轮验证,当前代码

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

@Entry
@Component
export struct Index{
  build(){
    Column(){
      SaveButton()
        .onClick(()=>{
          this.downloadFile();
        })
    }.width("100%")
    .height("100%")
  }

  downloadFile(){
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir = context.cacheDir;
    let url = 'https://yfd-aries-online.fbcontent.cn/resource/1729504315707_md5_7d7e3eb6a74eef238ac40cbc924e1267.jpeg';
    try {
      let encodedUrl = url
      let times=new Date();
      let name=times.getTime();
      request.downloadFile(context, {
        url: encodedUrl,
        filePath: filesDir + '/' + `${name}girl.png`,
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('complete', () => {
          console.info('download complete');
        })
        downloadTask.on('fail', (code) => {
          console.info(`download fail: ${code}`);
        })
      }).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}`);
    }
  }
}

可以下载,1.注意每次下载的文件名不能一致,2.在模拟器环境下,下载会失败,真机环境已经验证可以下载

更多关于下载HarmonyOS 鸿蒙Next资源文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


谢谢,换真机是可以了,

测试Demo:

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

@Entry
@Component
export struct Index3{
  build() {
    Column(){
      SaveButton()
        .onClick(()=>{
          this.downloadFile();
        })
    }.width("100%")
    .height("100%")

  }

  downloadFile() {
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir = context.filesDir;
    try {
      let encodedUrl = encodeURI('https://yfd-aries-online.fbcontent.cn/resource/1729504315707_md5_7d7e3eb6a74eef238ac40cbc924e1267.jpeg')
      request.downloadFile(context, {
        url: encodedUrl,
        filePath: filesDir + '/1729504315707_md5_7d7e3eb6a74eef238ac40cbc924e1267.jpeg',
        enableMetered: true,
        enableRoaming: true,
        header: {},
        networkType: request.NETWORK_WIFI,
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('complete', () => {
          console.info('download complete');
        })
        downloadTask.on('fail', (code) => {
          console.info(`download fail: ${code}`);
        })
      }).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}`);
    }
  }
}

module.json5添加权限:

{
        "name": "ohos.permission.INTERNET",
        "reason": "$string:EntryAbility_desc",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ]
        }
      }

开发者您好,request第一个可以下载成功,第二个不行,怀疑是url的链接问题,烦请对url进行编码,再进行尝试,代码可以参考如下:

let encodedUrl = encodeURI(url);
try {
  request.downloadFile(getContext(), { url: encodedUrl }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    let completeCallback = () => {
      console.info('Download task completed.');
    };
    downloadTask.on('complete', completeCallback);

    let failCallback = () => {
      console.info('Download task fail.');
    };
    downloadTask.on('fail', failCallback);
  }).catch((err: BusinessError) => {
    console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
  })
} catch (err) {
  console.error(`Failed to request the download. err: ${JSON.stringify(err)}`);
}

您好试了下还是不行,只要是https的下载都不行

使用会报错:download fail: 2 这个错误码2:Incorrect parameter type 到底是什么原因啊,看文档一脸懵

let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
try {
  let encodedUrl = encodeURI('<a class="autoSetLinkTag" href="https://yfd-aries-online.fbcontent.cn/resource/1729504315707_md5_7d7e3eb6a74eef238ac40cbc924e1267.jpeg" target="_blank" rel="nofollow">https://yfd-aries-online.fbcontent.cn/resource/1729504315707_md5_7d7e3eb6a74eef238ac40cbc924e1267.jpeg</a>')
  request.downloadFile(context, {
    url: encodedUrl,
    filePath: filesDir + '/1729504315707_md5_7d7e3eb6a74eef238ac40cbc924e1267.jpeg',
    enableMetered: true,
    enableRoaming: true,
    header: {},
    networkType: request.NETWORK_WIFI,
  }).then((downloadTask: request.DownloadTask) => {
    downloadTask.on('complete', () => {
      console.info('download complete');
    })
    downloadTask.on('fail', (code) => {
      console.info(`download fail: ${code}`);
    })
  }).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}`);
}

稍安勿躁,

图片没下成功的原因是的filePath一直没变过。

  1. 先卸载,再重装你的app,可以下载成功一次
  2. 每次使用修改filePath。 最终是需要删除同名文件,或者每次改下你的filePath。

针对帖子标题“下载HarmonyOS 鸿蒙Next资源文件”的问题,以下是专业且简洁的回答:

HarmonyOS 鸿蒙Next的资源文件下载通常涉及官方渠道或特定的开发者平台。为了获取这些资源文件,请遵循以下步骤:

  1. 访问官方开发者网站:首先,前往HarmonyOS的官方开发者网站,这是获取最新、最安全资源文件的最佳途径。

  2. 登录开发者账号:确保您已注册并登录了HarmonyOS开发者账号。如果尚未注册,请先完成注册流程。

  3. 查找资源下载区域:在开发者网站上,导航至资源下载或相关区域。这里通常会提供SDK、模拟器、示例代码等资源文件的下载链接。

  4. 选择HarmonyOS 鸿蒙Next版本:在下载区域中,找到与HarmonyOS 鸿蒙Next相对应的资源文件版本,并点击下载。

  5. 遵循下载和安装指南:下载完成后,仔细阅读并遵循官方提供的下载和安装指南,以确保资源文件正确安装和使用。

请注意,由于HarmonyOS是一个持续更新的操作系统,因此资源文件的下载链接和版本可能会随时间而变化。如果无法找到所需的资源文件或遇到下载问题,请直接访问官网客服寻求帮助。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部