如何强制下载文件提示而不是在浏览器中使用 HTML 显示它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23825871/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:52:08  来源:igfitidea点击:

How to force a Download File prompt instead of displaying it in-browser with HTML?

html

提问by UI_Dev

 <a href="sample.pdf" target="_blank">Download</a>

If I click Download button, this target blank is opening a new window.

如果我单击“下载”按钮,则此目标空白将打开一个新窗口。

But I need it to prompt a dialog for saving this file. How can I achieve this? enter image description here

但我需要它来提示保存此文件的对话框。我怎样才能做到这一点? 在此处输入图片说明

回答by Kostas Rousis

This is something that you cannot absolutely control with HTML itself.

这是您无法通过 HTML 本身完全控制的事情。

If the user is having a browser with PDF reading capabilities (or a plugin) and the corresponding settings to open PDF files in-browser, the PDF will open like that.

如果用户使用具有 PDF 阅读功能(或插件)的浏览器以及在浏览器中打开 PDF 文件的相应设置,则 PDF 将像这样打开。

The PDF opens in a new tab simple because of your target="_blank", which has nothing to do with a download prompt.

由于您的target="_blank",PDF 在一个新选项卡中打开很简单,这与下载提示无关。

If you are using HTML5 you can use the download attribute:

如果您使用的是 HTML5,则可以使用下载属性

<a href="sample.pdf" download="sample.pdf">Download</a>

If you have a back-end service which you can control or you feel like fiddling with your Web Server, you can always look for setting the right Content-Disposition. See this SO question for some nice discussion on Content-Disposition.

如果您有一个可以控制的后端服务,或者您想摆弄您的 Web 服务器,您可以随时寻找设置正确的Content-Disposition. 有关Content-Disposition 的一些不错的讨论,请参阅此 SO 问题。