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

HarmonyOS
2天前
浏览
收藏 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}`);
  });
}
分享
微博
QQ
微信
回复
2天前
相关问题