>我想下载一个带有javascript的pdf文件。文件内容将以 base64 编码。
请帮助我调查为什么我无法下载pdf文件。
索引.php:
<?php
$file_content = base64_encode(file_get_contents("1.pdf"));
?>
<!DOCTYPE>
<html>
<head>
<title>Download PDF </title>
</head>
<body>
<div>Hello World!</div>
<input type="button" onclick="download()" value="download"/>
<script>
function download() {
var str = "<?php echo $file_content;?>";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var data = window.atob(str);
var blob = new Blob([data], {type: "application/pdf"});
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "download.pdf";
a.click();
window.URL.revokeObjectURL(url);
}
</script>
</body>
</html>
基于这篇 Medium 帖子,这里有一个直接使用 base64 字符串的解决方案:
function download() {
var a = document.createElement("a");
a.style = "display: none";
a.href = "data:application/pdf;base64,<?= $file_content ?>";
a.download = "download.pdf";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
延伸阅读: Data_URIs
>download
属性将帮助您下载文件。
var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
另一种可能的解决方案:
如果要使用 blob 内容下载它,则必须将返回响应声明为arraybuffer
例:
$http.post('/postmethod',{params}, {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
将PDF文件打开到新窗口中,您可以从中保存它。