【发布时间】:2021-12-05 13:33:35
【问题描述】:
我有一个输入 URL,我想直接下载 pdf 文件而不在新选项卡或同一个选项卡中查看它,我一直尝试遵循一些事情,但没有任何帮助。首先尝试了这个
http.success(function (data) {
var link = document.createElement('a');
link.href = data.results[0].value.url;
link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
link.click();
document.body.appendChild(link);
setTimeout(function () {
document.body.removeChild(link);
}, 100);
}.bind(this));
此脚本未下载文件。它在同一选项卡中打开文件。 已经尝试了这些先前回答的问题中的所有答案。但没有什么对我有用。 How can I download a pdf from a url using javascript? How to download PDF automatically using js? Download pdf without opening in browser
然后我尝试使用这个 Blob。将 blob 添加到我的脚本中,然后重试。
http.success(function (data) {
var blob=new Blob([data.results[0].value.url],{ type: "application/pdf" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
link.click();
document.body.appendChild(link);
setTimeout(function () {
document.body.removeChild(link);
}, 100);
}.bind(this));
但这一次它下载了文件。但是打不开。下载的文件已损坏。 已经尝试过这些问题的答案。但没有什么对我有用。 PDF is corrupted after reconstructing it using URL.createObjectURL Problem downloading a PDF blob in JavaScript Blob from buffer returns corrupted pdf
如果有其他方法可以直接下载 pdf 文件,请告诉我。提前致谢。
【问题讨论】:
标签: javascript pdf