HarmonyOS 如何将一个excel文件下载保存到公共目录下?最好有demo

HarmonyOS
4天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

参考demo如下:

  downloadSave() {
    let context = getContext(this) as common.UIAbilityContext;
    let filePath = context.filesDir+"/test5.xlsx";
    let url ="在线表格文件链接名.xlsx"
    try {
      request.downloadFile(context, {
        url : url,
        filePath: filePath
      }).then((data:request.DownloadTask)=>{
        let downloadTask: request.DownloadTask = data;
        downloadTask.on('complete',()=>{
          console.info('download complete');
          let file = fs.openSync(filePath,fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
          let arrayBuffer = new ArrayBuffer(4096000);
          let readLen = fs.readSync(file.fd, arrayBuffer);
          let buf = buffer.from(arrayBuffer,0,readLen);
          console.info(`content of File: ${buf.toString()}`);
          let writeLen = fs.writeSync(file.fd, arrayBuffer);
          fs.closeSync(file);

          const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文件管理器选项实例
          documentSaveOptions.newFileNames = ["1.xlsx"]; // 保存文件名(可选)
          documentSaveOptions.fileSuffixChoices = ['xlsx']; // 保存文件类型(可选)
          let uris: Array<string> = [];
          const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例
          documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
            uris = documentSaveResult;
            console.info('documentViewPicker.save to file succeed and uris are:' + uris);

            let uri = uris[0];
            let file2 = fs.openSync(uri,fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
            let writeLen2 = fs.writeSync(file2.fd, arrayBuffer);
            fs.closeSync(file2);
          }).catch((err: BusinessError) => {
            console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
          })
        })

        let failCallback = () => {
          console.info('Download task fail.');
        };
        downloadTask.on('fail', failCallback);

      }).catch((err:BusinessError)=>{
        console.error(`downLoadFileTask failed, code is ${err.code}, message is ${err.message}`);
      });
    } catch (error){
      console.error(`downLoadFileTask failed, code is ${error.code}, message is ${error.message}`);
    }
  }
分享
微博
QQ
微信
回复
4天前
相关问题
如何将Pixmap保存到本地文件
547浏览 • 1回复 待解决
HarmonyOS 下载文件保存到指定目录
165浏览 • 1回复 待解决
如何将像素点保存到图片文件
2381浏览 • 1回复 待解决
HarmonyOS如何将PixelMap保存到相册?
653浏览 • 1回复 待解决
HarmonyOS 如何将图片保存到相册
63浏览 • 1回复 待解决
java怎么读取公共目录下文件
2318浏览 • 1回复 待解决
如何将段文字保存到剪切板中?
394浏览 • 1回复 待解决
如何将视频保存到相册以及主机端
5688浏览 • 1回复 待解决
HarmonyOS 如何将base64的图片保存到相册
1076浏览 • 1回复 待解决