HarmonyOS鸿蒙Next中在napi里面怎么保存文件到DOWNLOAD

HarmonyOS鸿蒙Next中在napi里面怎么保存文件到DOWNLOAD 如下代码所示,我使用 ArkTS代码保存到 DOWNLOAD 目录里,已经成功了。

现在遇到总是, 我的文件是从native端传过来的, 发现好像有大小限制,数据太大了,会Crash ,

所以,想问一下,

在 native 端,怎么保存文件到 DOWNLOAD

async saveImageFile(context: common.UIAbilityContext, fileName : string, buffer: ArrayBuffer) : Promise<boolean>{

  // 创建文件保存选项实例
  const documentSaveOptions = new picker.DocumentSaveOptions();
  documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD; // 设置为下载模式
  documentSaveOptions.newFileNames = [fileName]; // 指定默认文件名(网页4、10)

  // 创建文件选择器实例
  const documentViewPicker = new picker.DocumentViewPicker();
  try {

  const documentSaveResult: Array<string> = await documentViewPicker.save(documentSaveOptions);
  console.error(` uriArray1: ${documentSaveResult}`);
const uri = documentSaveResult[0];
console.info(' documentViewPicker.save succeed and uri is:' + uri);

// 基础路径(用户选的)
const basePath = new fileUri.FileUri(uri).path;
 
// 3. 最终文件路径
const targetPath = `${basePath}/${fileName}`;
const file = fs.openSync(targetPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
fs.writeSync(file.fd, buffer);
fs.closeSync(file.fd);

return true;
} catch(e) {
  const err = e as BusinessError;
  console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
  return false;
};

}

更多关于HarmonyOS鸿蒙Next中在napi里面怎么保存文件到DOWNLOAD的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS鸿蒙Next的NAPI环境中,使用OH_FileAccessHelper模块保存文件到DOWNLOAD目录。通过OH_FileAccess_CreateFileAccessHelper创建helper实例,调用createFile指定目标路径为Download目录URI,使用write接口写入数据流。需申请ohos.permission.WRITE_DOWNLOAD权限。

更多关于HarmonyOS鸿蒙Next中在napi里面怎么保存文件到DOWNLOAD的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next的NAPI中,可以通过以下方式将大文件保存到DOWNLOAD目录:

  1. 使用napi_get_value_string_utf8获取文件路径参数
  2. 通过OH_FileIO_OpenOH_FileIO_Write分块写入文件数据
  3. 设置DOWNLOAD目录路径:/storage/emulated/0/Download/

关键代码示例:

napi_status status;
size_t path_len;
char file_path[256];
status = napi_get_value_string_utf8(env, args[0], file_path, sizeof(file_path), &path_len);

const char* download_path = "/storage/emulated/0/Download/";
char full_path[512];
snprintf(full_path, sizeof(full_path), "%s%s", download_path, file_path);

int fd = OH_FileIO_Open(full_path, O_CREAT | O_WRONLY, 0644);
if (fd > 0) {
    OH_FileIO_Write(fd, data_buffer, data_size);
    OH_FileIO_Close(fd);
}

这种方法避免了内存限制问题,支持大文件的分块写入。

回到顶部