#鸿蒙通关秘籍#如何在HarmonyOS NEXT中保存下载的文件并预览

HarmonyOS
2024-12-02 15:12:27
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
紫电清霜EVT

创建一个方法下载文件并预览:

function dowLoadFile(data, handler, preview) {
  let context = getContext(this);
  let fileName = data.name;
  let filesDir = context.filesDir;
  let filePath = filesDir + '/' + fileName;
  request.downloadFile({
    url: data.url,
    filePath: filePath,
    enableMetered: true
  }).then(downloadTask => {
    downloadTask.on('progress', (receivedSize, totalSize) => {
      console.info(`Download progress: ${receivedSize} of ${totalSize}`);
    });
    
    downloadTask.on('complete', async () => {
      console.info('Download complete');
      if (preview) {
        previewFile(filePath);
      } else {
        const documentSaveOptions = new picker.DocumentSaveOptions();
        documentSaveOptions.newFileNames = [data.name];
        
        const documentViewPicker = new picker.DocumentViewPicker(context);
        documentViewPicker.save(documentSaveOptions).then(documentSaveResult => {
          let uri = documentSaveResult[0];
          let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
          let writeLen = fs.writeSync(file, new ArrayBuffer(99999999));
          fs.closeSync(file);
          promptAction.showToast({ message: '下载成功,保存到:' + uri, duration: 1000 });
        });
      }
    });
  }).catch(error => {
    console.error(`下载失败: ${error.code}, message: ${error.message}`);
  });
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
分享
微博
QQ
微信
回复
2024-12-02 16:47:09
相关问题
HarmonyOS 下载文件保存到指定目录
1181浏览 • 1回复 待解决
HarmonyOS 文件下载预览
809浏览 • 1回复 待解决