HarmonyOS鸿蒙Next中下载文件保存到本地

HarmonyOS鸿蒙Next中下载文件保存到本地 第一次点击下载 保存在本地 第二次再次点击 这个时候 文件已经在本地了 如何判断 文件已经存在 不走下载 而是直接找到这个文件

Button("保存2").onClick(() => {
  try {
    request.downloadFile(context, {
      url: "https://cfmoto.oss-cn-hangzhou.aliyuncs.com/upload/audio/AE863091060020422/audio_1.mp3",
      filePath: filesDir + '/11.mp3'
    }).then((downloadTask: request.DownloadTask) => {
      downloadTask.on('complete', () => {
        let file = fs.openSync(filesDir + '/11.mp3', fs.OpenMode.READ_WRITE);
        console.info('file.fd: ' + file.fd)
        console.info('file.fd: ' + JSON.stringify(filesDir + '/11.mp3'))
        let arrayBuffer = new ArrayBuffer(1024);
        let readLen = fs.readSync(file.fd, arrayBuffer);
        let buf = buffer.from(arrayBuffer, 0, readLen);
        console.info('file.fd1: ' + JSON.stringify(buf))
        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}`);
  }
})

更多关于HarmonyOS鸿蒙Next中下载文件保存到本地的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复
try {
  const fileExists = await fs.accessSync(filePath);
  if (fileExists) {
    console.info('文件已存在,进行操作...');
    this.processExistingFile(filePath);
  } else {
    console.info('文件不存在,开始下载...');
    this.downloadFile(url, filePath);
    console.info('文件下载完成');
    this.processExistingFile(filePath);
  }
} catch (err) {
  console.error('操作失败:', err);
}

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


在HarmonyOS鸿蒙Next中,下载文件并保存到本地可以通过使用DownloadManager类来实现。首先,你需要创建一个DownloadManager.Request对象,并设置下载的URL、保存路径等参数。然后,将这个请求添加到DownloadManager中,系统会自动处理下载任务。

具体步骤如下:

  1. 创建DownloadManager.Request对象:

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
    
  2. 设置保存路径和文件名:

    request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, fileName);
    
  3. 添加请求到DownloadManager

    DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    long downloadId = downloadManager.enqueue(request);
    
  4. 监听下载状态:

    可以通过注册BroadcastReceiver来监听下载完成或失败的事件。

    BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (id == downloadId) {
                // 下载完成处理逻辑
            }
        }
    };
    context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    

通过以上步骤,你可以在HarmonyOS鸿蒙Next中实现文件下载并保存到本地的功能。

在HarmonyOS鸿蒙Next中下载文件并保存到本地,可以使用DownloadManager服务。首先,通过getSystemService(Context.DOWNLOAD_SERVICE)获取DownloadManager实例。然后,创建DownloadManager.Request对象,设置下载URL和保存路径。最后,调用downloadManager.enqueue(request)开始下载。下载完成后,文件将保存到指定路径,可通过DownloadManager查询下载状态和文件位置。

回到顶部