我正在尝试将 HyperLink 控件的NavigateUrl
路径设置为文件,以便用户可以单击链接并下载文件。在我的 C# 和 ASPX 代码中,URL 似乎设置正确,但单击链接不会导致任何事情发生;右键单击链接并尝试保存链接尝试保存download.htm
.
在幕后,我在 temp 目录中创建文件并将其移动到可用位置以供下载。这部分有效;我把它包括在内以供参考。
private string MoveFile(string file_name, string file_path)
{
string tempdir = HttpContext.Current.Server.MapPath( ConfigurationManager.AppSettings["docs_folder"] );
string new_file_name = Path.Combine( tempdir, Path.GetFileName( file_name ) );
try
{
if (File.Exists( new_file_name ))
{
File.Delete( new_file_name );
}
File.Move( file_name, new_file_name );
}
catch (Exception e)
{
string message = e.Message;
}
return new_file_name;
}
以下是我目前设置 URL 的方式:
string download_file = downloader.DownloadFiles(); //Ultimately returns the path from the MoveFile method
hl_download.NavigateUrl = "file:///" + HttpUtility.UrlPathEncode( download_file ).Replace("\\","//");
hl_download.Visible = true;
我的输出看起来像:
file:///C://users//codes%20with%20hammer//documents//visual%20studio%202012//Projects//Download%20File//Download%20File//Archive_to_download.zip
当我将此 URL 直接放入浏览器时,文件会正确下载。那么为什么它在超链接上不起作用呢?
我还尝试在静态超链接上设置属性。结果相同。为了比较:
<asp:HyperLink ID="HyperLink1" runat="server" Visible="True" NavigateUrl="file:///C:/users/codes%20with%20hammer/documents/visual%20studio%202012/Projects/Download%20File//Download%20File//Archive_to_download.zip">click me</asp:HyperLink>
修改
我的 ASHX 页面中包含以下代码ProcessRequest
:
context.Response.Clear();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader( "Content-Disposition", "attachment; filename=" + Path.GetFileName( download_file ));
context.Response.WriteFile( context.Server.MapPath( download_file ) );
context.Response.End();
也许我应该把它移到我的代码隐藏文件中?