javascript 如何强制超链接显示打开/保存对话框而不是在浏览器中打开它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9901326/
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
How to force a hyperlink to show the open/save dialog box instead of opening it in browser?
提问by Manas Saha
In my code I am generating several hyperlinks dynamically which are direct links to PDF/Jpg/bitmap/Png/Docx/Xlsx/Pptx files hosted in the server.
在我的代码中,我动态生成了几个超链接,它们是指向服务器中托管的 PDF/Jpg/bitmap/Png/Docx/Xlsx/Pptx 文件的直接链接。
the code looks somewhat like this.
代码看起来有点像这样。
private void PopulateLinks(string linkText, string URL)
{
DIV_download.innerHtml += "<a href='" + URL + "'>" + linkText + "</a> <br/>";
}
The problem is whatever files browser can handle, it is opening in the same tab. is there any way to force the download dialog box for PDF and JPEG/Bitmap/Png files?
问题是浏览器可以处理的任何文件,它都在同一个选项卡中打开。有没有办法强制下载PDF和JPEG/Bitmap/Png文件的对话框?
Since I need this in client side, I can not use the content-dispostion way, can it be done using javascript or any other markup? My clients only use internet explorer so it will be enough for me if it works only in IE.
由于我在客户端需要这个,我不能使用内容处理方式,可以使用 javascript 或任何其他标记来完成吗?我的客户只使用 Internet Explorer,所以如果它只适用于 IE,对我来说就足够了。
回答by m.mehta
try
Content-Disposition: attachment
property in your code
example of my code:
Content-Disposition: attachment
在我的代码的代码示例中尝试
属性:
response.setHeader("Content-Disposition: attachment", "filename=\"" + filePath + "\"");
回答by Jeff
I'm pretty sure you cannot do this client side. However you could add a target=_blank attribute to the link tag. That will force it to open in a new window. Or you could have your client right click the link and Save Target As.
我很确定你不能做这个客户端。但是,您可以向链接标记添加 target=_blank 属性。这将强制它在新窗口中打开。或者您可以让您的客户右键单击该链接并将目标另存为。
回答by Mike Chamberlain
You can do this in IE by using the DOM method document.execCommand():
您可以在 IE 中使用 DOM 方法 document.execCommand() 来执行此操作:
<a href="javascript:void(0);"
onclick="document.execCommand('SaveAs',true,'file.html');"
>Save this page</a>
This if from http://www.jtricks.com/bits/content_disposition.html. You will probably have to investigate cross-browser compatibility.
如果来自http://www.jtricks.com/bits/content_disposition.html。您可能需要调查跨浏览器的兼容性。
There is also information in this question that may be of interest for working with non-IE browsers: Cross-browser Save As .txt
这个问题中还有一些信息可能对使用非 IE 浏览器感兴趣: Cross-browser Save As .txt