HarmonyNEXT单文件下载及保存到用户文件

需求:从后台给的文件地址下载到本地,并让用户保存在文件夹中。

后来测试进行二次修改,现在下载文件都没有问题。

API : API Version 12 Beta5
Dev : 5.0.3.700

一、基础

先熟悉几个File文件操作的方法。

  1. 判断文件是否存在:
import fs from '@ohos.file.fs';

 //判断文件是否存在
  fs.access(filePath).then((res: boolean) => {
        if (res) {
          Log.info("文件存在")
          
        } else {
          Log.info("文件不存在")
         
        }
      }).catch((err: BusinessError) => {
        Log.error("access failed with error message: " + err.message + ", error code: " + err.code);
      });

  1. 删除文件:
import fs from '@ohos.file.fs';

fs.unlinkSync(filePath)
  1. 获取文件长度:
import fs from '@ohos.file.fs';

fs.lstatSync(filePath).size
  1. 官方下载上传文件文档

  2. 官方保存/选择文件文档

二、工具类封装

因考虑到可能下载文件会出现在多线程场景,并没有写成单例,可根据需求修改。

LoadingDialog:https://ohpm.openharmony.cn/#/cn/detail/@lyb%2Floading-dialog

import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { Log } from './Log';
import { fileIo, picker } from '@kit.CoreFileKit';
import { promptAction } from '@kit.ArkUI';
import LoadingDialog from '@lyb/loading-dialog';

/**
 * 下载文件及打开工具类
 */
export class DownloadFileUtil {
  /**
   * 开始下载文件 设置文件下载路径 校验文件是否存在
   */
 startDownFile(downPath: string) {
    let pathList = downPath.split("/")
    //文件名称
    let fileName = pathList[pathList.length-1]
    let context = getContext(this) as common.UIAbilityContext;
    //文件保存在应用沙箱路径
    let filePath = context.filesDir + fileName
    Log.info("文件路径:"+filePath)
    Log.info("下载地址:"+downPath)
    try {
      fs.access(filePath).then((res: boolean) => {
        if (res) {
          Log.info("文件存在")
          fs.unlinkSync(filePath)
          this.downloadFile(context, downPath, filePath, fileName)
        } else {
          Log.info("文件不存在")
          this.downloadFile(context, downPath, filePath, fileName)
        }
      }).catch((err: BusinessError) => {
        Log.error("access failed with error message: " + err.message + ", error code: " + err.code);
      });

    } catch (error) {
      let err: BusinessError = error as BusinessError;
      Log.error("startDownFile:"+err.message)
    }
  }

  /**
   * 下载文件
   * @param downPath 下载地址
   * @param filePath  下载保存路径
   * @param fileName  文件名称
   */
  downloadFile(context: Context, downPath: string, filePath: string, fileName: string) {
    LoadingDialog.showLoading("下载中...")
    request.downloadFile(context, {
      url: downPath,
      filePath: filePath
    }).then((downloadTask: request.DownloadTask) => {
      let progressCallback = (receivedSize: number, totalSize: number) => {
        Log.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
      };
      downloadTask.on('progress', progressCallback);

      downloadTask.on('complete', () => {
        LoadingDialog.hide()
        Log.info('download complete');
        Log.error("文件大小:" + fs.lstatSync(filePath).size) //看看文件是否下载正常

        this.savePath(filePath, fileName)
      })
    }).catch((err: BusinessError) => {
      LoadingDialog.hide()
      Log.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
    });
  }

  /**
   * 保存文件
   * @param filePath 应用沙箱文件地址
   * @param fileName  文件名称
   */
  savePath(filePath: string, fileName: string) {
    try {
      let uri: string = '';
      let DocumentSaveOptions = new picker.DocumentSaveOptions();
      DocumentSaveOptions.newFileNames = [fileName];
      let documentPicker = new picker.DocumentViewPicker();
      //调用API拉起保存功能
      documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult: Array<string>) => {
        uri = DocumentSaveResult[0];
        let downFile = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE);
        let file = fileIo.openSync(uri, fileIo.OpenMode.READ_WRITE);

        Log.info("下载文件路径:" + downFile.path + ",用户地址:" + file.path)
			
        fileIo.copyFile(downFile.path, file.path).then(() => {
          promptAction.showToast({ message: "保存成功" })
          fileIo.closeSync(file.fd);
          fileIo.closeSync(downFile.fd);
        }).catch(() => {
          promptAction.showToast({ message: "保存失败" })
          fileIo.closeSync(file.fd);
          fileIo.closeSync(downFile.fd);
        }

      }).catch((err: BusinessError) => {
        Log.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      Log.error('DocumentViewPicker failed with err: ' + err.message);
    }
  }
}

三、总结

鸿蒙文件处理这块还是相对复杂,很多API根据需求继续研究【文件管理】。

最后,有个需求希望大家给个建议:我想在线预览word、pdf、ppt、Excel等文件,各位同仁有好的建议评论区回复我,感谢~

<think>嗯,用户问的是如何在HarmonyOS中进行文件写入的静态声明,需要示例。首先,我得确定用户所说的“静态声明”具体指什么。在开发中,“静态声明”可能涉及权限的声明或者文件路径的配置,这部分通常在配置文件中进行。 根据之前的引用内容,用户提到了资源目录结构和示例代码。比如引用[3]中提到了项目结构中的resources目录和开发步骤,可能需要用到配置文件HarmonyOS中,文件操作通常需要声明权限,比如读写存储的权限。所以,静态声明可能包括在config.json里的权限声明和文件路径配置。 然后,我需要查找HarmonyOS的文档,确认文件写入所需的权限。一般来说,需要ohos.permission.WRITE_USER_STORAGE权限。同时,文件路径可能放在rawfile或其它目录下,但实际写入可能需要使用应用沙箱路径,比如使用Context获取文件路径。 接下来,示例代码部分需要展示如何声明权限,如何在代码中使用文件API进行写入。可能要用到@ohos.fileio模块的API,比如open和write。同时,要确保代码符合ETS的语法,比如使用async/await处理异步操作。 另外,用户可能需要区分静态声明和动态权限申请。静态声明是在配置文件中预先声明需要的权限,而动态申请是在运行时请求用户授权。这里用户问的是静态声明,所以重点在config.json的配置。 可能还需要考虑文件路径的正确处理,比如使用系统提供的沙箱路径,而不是硬编码路径,以确保应用在不同设备上的兼容性。 总结步骤应该是:1. 在config.json中声明写入权限;2. 在代码中使用文件API进行写入操作,并处理异步流程;3. 确保路径正确,使用应用上下文获取合适的目录。 最后,生成相关问题,帮助用户进一步学习,比如动态权限申请、文件读取、不同存储位置的区别等。</think>在HarmonyOS中进行文件写入的静态声明需要结合权限声明与API调用,以下是具体实现步骤和示例: ### 一、文件写入静态声明实现步骤 1. **权限声明**:在`config.json`中声明文件操作权限 ```json "reqPermissions": [ { "name": "ohos.permission.WRITE_USER_STORAGE" // 用户存储写入权限[^1] } ] ``` 2. **文件路径声明**(可选): ```typescript const CONTEXT: Context = getContext(this); const FILE_PATH = CONTEXT.filesDir + "/demo.txt"; // 应用沙箱路径[^3] ``` ### 二、完整文件写入示例 ```typescript import fileio from '@ohos.fileio'; async function writeFile(content: string) { try { let file = await fileio.open(FILE_PATH, 0o102, 0o666); // 0o102表示创建+写入模式 await fileio.write(file.fd, content); fileio.close(file.fd); console.log("写入成功"); } catch (e) { console.error("写入失败:" + e); } } // 调用示例 writeFile("Hello HarmonyOS"); ``` ### 三、关键要点说明 1. **权限类型**: - `ohos.permission.READ_USER_STORAGE` 读取权限 - `ohos.permission.WRITE_USER_STORAGE` 写入权限 2. **文件模式参数**: ```typescript 0o100 // 只读 0o102 // 创建+写入(类似O_CREAT|O_WRONLY) 0o2002 // 追加模式 ``` 3. **存储位置选择**: - `filesDir`:应用私有目录(无需声明权限) - `tempDir`:临时文件目录 - 外部存储需声明上述权限
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值