HarmonyOS 鸿蒙Next 保存沙箱路径下的pdf到手机文件管理中

发布于 1周前 作者 songsunli 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 保存沙箱路径下的pdf到手机文件管理中

Button(“saveDocument()”) 
.btnStyle()
.onClick(() => {
let fileName = test_${DateUtil.getTodayTime()}.pdf;
PickerUtil.saveDocument([fileName]).then((uris) => {
let uri = uris[0];
this.uriStr = 调用保存文件,返回uris:\n${uri}

let filePath = this.path
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
let arrayBuffer = new ArrayBuffer(4096);
fs.read(file.fd, arrayBuffer).then((readLen: number) => {
console.info(“read file data succeed”);
let buf = buffer.from(arrayBuffer, 0, readLen);
FileUtil.writeEasy(uri, buf.buffer)
.then(() => {
this.uriStr = 文件保存成功,返回uris:\n${uri}
ToastUtil.showToast(“文件保存成功”);
})
}).catch((err: BusinessError) => {
console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
}).finally(() => {
fs.closeSync(file);
});
}).catch((err: BusinessError) => {
this.uriStr = 调用保存文件,异常:\n${JSON.stringify(err)}
})
})
}.width(“100%”).height(100).justifyContent(FlexAlign.Center)


更多关于HarmonyOS 鸿蒙Next 保存沙箱路径下的pdf到手机文件管理中的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复
import { common } from '@kit.AbilityKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { buffer } from '@kit.ArkTS';
import { picker, storageStatistics } from '@kit.CoreFileKit';
import { webview } from '@kit.ArkWeb';

let context = getContext(this) as common.UIAbilityContext;

@Entry @Component struct testPdfSave { testIndex: number = 0;

build() { Column() { Button(‘保存’).onClick(() => { let filePath = context.cacheDir + “/test” + this.testIndex + “.pdf”; this.testIndex = this.testIndex + 1 let url = https://gitee.com/harmonyos-cases/cases/raw/master/CommonAppDevelopment/feature/webpdfviewer/src/main/resources/rawfile/sample.pdf try { request.downloadFile(context, { url: url, background: true, filePath: filePath }).then((data: request.DownloadTask) => { let downloadTask: request.DownloadTask = data;

        downloadTask.on(<span class="hljs-string">'complete'</span>, () =&gt; {
          console.info(<span class="hljs-string">'download complete'</span>);
          <span class="hljs-keyword">let</span> file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
          <span class="hljs-keyword">let</span> arrayBuffer = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">4096000</span>);
          <span class="hljs-keyword">let</span> readLen = fs.readSync(file.fd, arrayBuffer);
          <span class="hljs-keyword">let</span> buf = buffer.from(arrayBuffer, <span class="hljs-number">0</span>, readLen);
          console.info(`content of File: ${buf.toString()}`);
          <span class="hljs-keyword">let</span> writeLen = fs.writeSync(file.fd, arrayBuffer);
          fs.closeSync(file);

          <span class="hljs-keyword">const</span> documentSaveOptions = <span class="hljs-keyword">new</span> picker.DocumentSaveOptions(); <span class="hljs-comment">// 创建文件管理器选项实例</span>
          documentSaveOptions.newFileNames = [<span class="hljs-string">"1.pdf"</span>]; <span class="hljs-comment">// 保存文件名(可选)</span>
          documentSaveOptions.fileSuffixChoices = [<span class="hljs-string">''</span>]; <span class="hljs-comment">// 保存文件类型(可选)</span>
          <span class="hljs-keyword">let</span> uris: <span class="hljs-built_in">Array</span>&lt;string&gt; = [];
          <span class="hljs-keyword">const</span> documentViewPicker = <span class="hljs-keyword">new</span> picker.DocumentViewPicker(); <span class="hljs-comment">// 创建文件选择器实例</span>
          documentViewPicker.save(documentSaveOptions).then((documentSaveResult: <span class="hljs-built_in">Array</span>&lt;string&gt;) =&gt; {
            uris = documentSaveResult;
            console.info(<span class="hljs-string">'documentViewPicker.save to file succeed and uris are:'</span> + uris);
            <span class="hljs-keyword">let</span> uri = uris[<span class="hljs-number">0</span>];
            <span class="hljs-keyword">let</span> file2 = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
            <span class="hljs-keyword">let</span> writeLen2 = fs.writeSync(file2.fd, arrayBuffer);
            fs.closeSync(file2);
          }).catch((err: BusinessError) =&gt; {
            console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
          })
        })

        <span class="hljs-keyword">let</span> failCallback = () =&gt; {
          console.info(<span class="hljs-string">'Download task fail.'</span>);
        };
        downloadTask.on(<span class="hljs-string">'fail'</span>, failCallback);

      }).catch((err: BusinessError) =&gt; {
        console.error(`downLoadFileTask failed, code is ${err.code}, message is ${err.message}`);
      });
    } <span class="hljs-keyword">catch</span> (error) {
      console.error(`downLoadFileTask failed, code is ${error.code}, message is ${error.message}`);
    }

  })
}
.height(<span class="hljs-string">'100%'</span>)
.width(<span class="hljs-string">'100%'</span>)

} }<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

更多关于HarmonyOS 鸿蒙Next 保存沙箱路径下的pdf到手机文件管理中的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS 鸿蒙Next系统中,保存沙箱路径下的PDF文件到手机文件管理中的操作,可以通过以下步骤实现:

  1. 获取文件访问权限:首先,确保你的应用已经获得了对文件系统的访问权限。这通常需要在应用的manifest.json文件中声明必要的权限,如读写存储权限。

  2. 读取沙箱文件:使用鸿蒙系统提供的API,从沙箱路径中读取PDF文件。你可以通过FileProvider或类似的机制来访问沙箱内的文件。

  3. 获取目标路径:确定要将PDF文件保存到的目标路径,这通常是手机文件管理中的某个公共目录,如“下载”或“文档”。

  4. 文件复制或移动:利用鸿蒙的文件操作API,将PDF文件从沙箱路径复制到目标路径。你可以使用File类或相关的文件操作类来完成这一步骤。

  5. 通知用户:操作完成后,可以通过系统通知或应用内的提示,告知用户文件已成功保存到指定的手机文件管理目录中。

请注意,上述步骤中的具体API和方法可能会因鸿蒙系统的版本和API的更新而有所变化。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部