1、项目中引入File插件,File插件使用参见https://ionicframework.com/docs/native/file
2、File下载文件实现代码示例
import { Injectable } from '@angular/core';
import { File } from '@ionic-native/file/ngx';
@Injectable({
providedIn: 'root'
})
export class FilesDownloadService {
constructor(
private file: File
) { }
/*
下载文件
fileid:附件id
filename:文件名称
*/
fileDownload(fileid: string,filename:string) {
const filedir = this.file.dataDirectory;//下载到手机内的文件路径
//调用webapi接口,下载文件,返回base64
this.attachfileService.downloadFile(fileid).subscribe(res => {
if (res.code == 200) {
const arrayBuffer = this.base64ToArrayBuffer(res.dataResult);
const blob = new Blob([arrayBuffer]);
this.file.createFile(filedir, filename, true).then(() => {
this.file.writeExistingFile(filedir, filename, blob).then(() => {
console.log("write file success");
}, err => {
console.log("write file error:" + JSON.stringify(err));
});
}, error => {
console.log("create file error:" + JSON.stringify(error));
});
}
}, e => {
console.log("download file error:" + JSON.stringify(e));
});
}
/*Base64到数组缓冲区 */
base64ToArrayBuffer(base64: string) {
const binaryString = window.atob(base64); //如果不使用base64,则注释这个
const bytes = new Uint8Array(binaryString.length);
return bytes.map((byte, i) => binaryString.charCodeAt(i));
}
}