HarmonyOS 文件保存,pdf、xlsx文件如何保存到本地?

使用DocumentViewPicker时选择保存文件路径后,在将本地文件复制到此路径下时报错,没有对应的目录

阅读 497
1 个回答

请参考以下demo(将沙箱路径中的readfile.xlsx复制到文件选择器中):

function SaveFile(context: common.UIAbilityContext) { // 需确保 context 由 UIAbilityContext 转换而来
  try {
    let documentSaveOptions = new picker.DocumentSaveOptions();
    documentSaveOptions.newFileNames = ['test5.xlsx'];
    let documentPicker = new picker.DocumentViewPicker(context);
    documentPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
      console.info('DocumentViewPicker.save successfully, documentSaveResult uri: ' +
      JSON.stringify(documentSaveResult));
      let uri = documentSaveResult[0]
      let Arraybuffer = new ArrayBuffer(1024 * 1024)
      let filesDir = getContext().filesDir
      //此次读长度
      let readLength = 0
      //已读长度
      let readTotalLength = 0
      //开始读的位置,这里设置为0
      let fitstOffset = 0
      //要读取的文件
      let readFile = fs.openSync(context.filesDir + '/readfile.xlsx', fs.OpenMode.READ_ONLY)
      //要写入的文件
      let writeFile = fs.openSync(uri, fs.OpenMode.READ_WRITE)
      //原文件总长度
      let stat = fs.statSync(filesDir + '/readfile.xlsx') as fs.Stat
      let length = stat.size
      try {
        while ((readLength = fs.readSync(readFile.fd, Arraybuffer,
          { offset: fitstOffset + readTotalLength, length: length > Arraybuffer.byteLength ? 1024 * 1024 : length })) >
          0) {
          readTotalLength += readLength
          fs.writeSync(writeFile.fd, Arraybuffer, { length: readLength })
          length -= Arraybuffer.byteLength
        }
      } catch (err) {
        console.log(err)
      }
      fs.closeSync(readFile)
      fs.closeSync(writeFile)

    }).catch((err: BusinessError) => {
      console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err));
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏