下面的代码不起作用。我想从链接按钮点击事件中的文件夹下载CSV文件。
protected void LinkButton1_Click(object sender, EventArgs e)
{
string filePath = "~/Data/Book1.csv";
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(filePath));
if (file.Exists)
{
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
//string filePath = "";
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=Filename.extension");
byte[] data = req.DownloadData(Server.MapPath(filePath));
response.BinaryWrite(data);
response.End();
}
}
答案 0 :(得分:0)
您可以直接将其传输到客户端,而不是使用WebClient
来读取文件。只要文件位于本地文件系统中,您就不需要使用Web请求获取它,但可以直接读取它。这样效率更高。
protected void LinkButton1_Click(object sender, EventArgs e)
{
string filePath = "~/Data/Book1.csv";
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(filePath));
if (file.Exists)
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.AddHeader("Content-Disposition", "Attachment;Filename=" + file.Name);
response.TransmitFile(file.FullName);
response.Flush();
response.End();
}
}
我还建议在结束响应之前禁用缓冲区并刷新内容。
同样@BobSwager指出,Content-Disposition
标题中存在一些问题。