简体   繁体   English

从链接下载文件

[英]Downloading a file from a link

I have a web page using C# where I want users to be able to click a link (or a linkbutton or a button, I'm not fussy) and have the "Save As" dialog window appear so they can download the file. 我有一个使用C#的网页,我希望用户能够点击链接(或链接按钮或按钮,我不挑剔)并显示“另存为”对话框窗口,以便他们可以下载文件。 The file itself is located on another server so I have to use the absolute path (i:\\division\\department\\publicfiles\\filename.pot). 文件本身位于另一台服务器上,因此我必须使用绝对路径(i:\\ division \\ department \\ publicfiles \\ filename.pot)。 Does anyone know how to do that? 有谁知道这是怎么做到的吗?

I looked up the question here and some people suggested webClient.DownloadFile. 我在这里查了一下这个问题,有人建议使用webClient.DownloadFile。 Except I can't use that because it requires that you already know where the user wants the file to be downloaded to on their computer. 除非我不能使用它,因为它要求您已经知道用户希望将文件下载到其计算机上的位置。 Basically what I'm looking for is what happens when you right click on a link and select "save as", but done when you left click on a link. 基本上我正在寻找的是当您右键单击链接并选择“另存为”时会发生什么,但是当您左键单击链接时就会完成。

Thank you 谢谢

"The file itself is located on another server" to me sounds like it might not be published to the web and thus doesn't have a URL. “文件本身位于另一台服务器上”听起来好像它可能没有发布到网络上,因此没有网址。 Therefore a simple anchor tag will not work in this case. 因此,在这种情况下,简单的锚标记将不起作用。 I think you're looking for Response.TransmitFile() . 我想你正在寻找Response.TransmitFile()

When they click on the link, you need to send the file and explicitly set the content type and content-disposition header. 当他们单击链接时,您需要发送文件并显式设置内容类型和内容处置标头。 Setting the content-disposition header to attachment will pop up the save as dialog. 将content-disposition标头设置为attachment将弹出另存为对话框。 Like (untested): 喜欢(未经测试):

Response.ContentType = "application/x-pot";    
Response.AppendHeader("Content-Disposition","attachment; filename=filename.pot");    
Response.TransmitFile(@"i:\division\department\publicfiles\filename.pot");    
Response.End();

你可以这样做,

<a href="http://www.yoursite.com/folders/yourfile.pdf"  target="_blank" > click to download file </a>

With HTML5 you could just use the new property download in the anchor tag. 使用HTML5,您可以在锚标记中使用新属性download

The code will look something like 代码看起来像

<a download href="path/to/the/download/file"> Clicking on this link will force download the file</a>

It works on firefox and chrome latest version. 它适用于firefox和chrome最新版本。 Should I mention that I didn't check it in IE? 我应该提一下我没有在IE中查看它吗? :P :P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM