javascript 单击按钮时强制下载 pdf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15173025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
forcing a pdf to download when clicked on button
提问by beNerd
I hava a backbonejs view containing a button saying "download pdf". I also have the url available where the pdf can be found. I want that when user clicks on the button, the pdf file gets downloaded. Is it possible?
我有一个主干视图,其中包含一个按钮,上面写着“下载 pdf”。我也有可以找到 pdf 的网址。我希望当用户点击按钮时,pdf 文件被下载。是否可以?
EDIT: My view code in backbone.js
编辑:我在backbone.js 中的视图代码
savendownload: function () {
this.$("#saveanddownload").button('loading');
var that = this;
var formData = this.fetchData();
if (formData) window.invoices.create({
buyer: formData.buyer,
items: formData.items,
company: formData.company,
action: "savendownload"
}, {
wait: true,
success: function (model) {
var data = model.toJSON();
var filename = data.filename;
//download code here
}
});
}
采纳答案by jevakallio
Don't use a button, use a link and set the hrefattribute to the URL of your PDF file. The browser will handle the file download for you, honoring the user's browser preferences.
不要使用按钮,使用链接并将href属性设置为PDF 文件的 URL。浏览器将为您处理文件下载,尊重用户的浏览器首选项。
<a href="your/file.pdf" />
If you need the link to look like a button, you can style it using CSS. See for example this SO thread.
如果您需要链接看起来像一个按钮,您可以使用 CSS 对其进行样式设置。例如,参见这个SO 线程。
Edit:AFAIK, you can't reliably initialize a file download from javascript. What you can do is to open a new window/tab with your pdf URL:
编辑:AFAIK,您无法可靠地从 javascript 初始化文件下载。您可以做的是使用您的 pdf URL 打开一个新窗口/选项卡:
window.open("http://domain.com/document.pdf",'_blank');
But the user's browser can block the new window from being created. You might want to simply generate a download link:
但是用户的浏览器可以阻止创建新窗口。您可能只想生成一个下载链接:
$('<a>Click here to download PDF</a>').attr('href', filename).appendTo(that.$el);
And have the user click the link to initiate the file download.
并让用户单击链接以启动文件下载。

