在下面的代码中,我想从本地下载文件,当我点击链接按钮时,它应该从特定路径下载文件。在我的情况下,它抛出
' C:/Search/SVGS/Documents/img.txt'是物理路径,但预计会有虚拟路径。
protected void lnkbtndoc_Click(object sender, EventArgs e)
{
LinkButton lnkbtndoc = new LinkButton();
var SearchDoc = Session["Filepath"];
string file = SearchDoc.ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + file + "\"");
Response.TransmitFile(Server.MapPath(file));
Response.End();
}
答案 0 :(得分:3)
使用以下代码在链接按钮上下载文件
<asp:LinkButton ID="btnDownload" runat="server" Text="Download"
OnClick="btnDownload_OnClick" />
protected void btnDownload_OnClick(object sender, EventArgs e)
{
string filename = "~/Downloads/msizap.exe";
if (filename != "")
{
string path = Server.MapPath(filename);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
}
答案 1 :(得分:0)
检查这些中的任何一个。
StreamReader Server.MapPath - Physical path given, virtual path expected
http://www.codeproject.com/Questions/624307/Server-MapPath-Physical-path-given-virtual-path-ex
答案 2 :(得分:0)
在您的代码中只需更改此行:
Response.TransmitFile(Server.MapPath(file));
到
Response.TransmitFile(file);
这是因为您发送的物理路径不是Server.MapPath
期望的虚拟路径。另请阅读此article,它将帮助您了解如何处理Server.MapPath
方法