我只是在检查从服务器下载的任何文件。以下代码可以在浏览器上使用,但不能在应用程序中使用。似乎下面的代码不工作
document.body.appendChild(downloadLink);
downloadLink.click();
我的完整代码:
downloadFile(directory: string, filename: string = null): void {
const baseUrl = this.service.Base_Url + 'download.php?dir=files/' + directory + '/&file=' + filename;
this.service.process_download(baseUrl).subscribe(
(response: any) => {
//Check Blob size | File is available or not
if (response.size > 0) {
let dataType = response.type;
let binaryData = [];
binaryData.push(response);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: dataType }));
if (filename) {
downloadLink.setAttribute('download', filename);
}
document.body.appendChild(downloadLink);
downloadLink.click();
}
}
)
}
过程功能:-
public process_download(url: any) {
if (this.Base_Url != undefined) {
return this.http.get(url, { responseType: 'blob' });
}
}
download.php是一个下载脚本。
//Download function starts from here
$varFilePath = SOURCE_ROOT . $varDir . $varFile;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=" . $varFile);
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($varFilePath));
header("Content-Description: File Transfer");
@readfile($varFilePath);
exit();
这是与浏览相关的代码,类似于纯javascript网站,因此它可以在浏览器中工作
你需要使用这个">文件传输";插件在本机设备中实现。https://ionicframework.com/docs/native/file-transfer
谢谢。