我从Web服务获取JSON响应,该服务返回二进制或base64中的文件.我想将此文件保存到fileSystem.
我还想知道我需要使用Phonegap FileAPi中的哪些方法?
我正在使用 Angular 9 / Ionic 5 / Capacitor 2.0 开发混合应用程序。我正在尝试将来自 API 的文件(基本上是 PDF 或图像文件)作为 Blob 保存到我的移动设备(IOS/Android)的文件系统中。我的最终目标是重现文件的类似浏览器的下载功能(允许用户将其保留在手机上)。
这是我的代码:
downloadNativeFile(blob: Blob, fileName: string){
let reader = this.getFileReader();
reader.onloadend = (readerEvent) => {
if(reader.error){
console.log(reader.error);
} else {
let base64data: any = readerEvent.target['result'];
try {
Filesystem.writeFile({
path: fileName,
data: base64data,
directory: FilesystemDirectory.Data
}).then((res)=>{
Filesystem.getUri({
directory: FilesystemDirectory.Data,
path: fileName
}).then((getUriResult) => {
const path = getUriResult.uri;
console.log("The file's path : " + path);
console.log(Capacitor.convertFileSrc(getUriResult.uri));
}, (error) => {
console.log(error);
});
}).catch((err)=>{
console.log("Error", err);
}); …Run Code Online (Sandbox Code Playgroud)