原理
- 要让浏览器弹出另存为的对话框,需要在http header里面设置恰当的content-type。浏览器会根据response里面的content-type来做不同的处理和响应
- 要想指定下载的默认文件名,需要设置Content-Disposition这个header。
- 要下载的文件,需要写入response的http body里面。想下载什么内容,写什么内容。
- Context.Response.End()会结束当前页面请求的处理,避免Page_Load之后的filter写额外的东西到http body去。
代码
if (exportcsv == 1 && Context.Request.HttpMethod == "POST")
{
Context.Response.ContentType = "text/csv";
Context.Response.AddHeader("Content-Disposition", "attachment;filename=mydata.csv");
foreach (DataRow row in ds.Tables[0].Rows)
{
Context.Response.Output.WriteLine(string.Format("{0},{1}", row["name"], row["age"]));
}
Context.Response.End();
return;
}
另外,csv文件下载之后有可能会中文乱码,可能会需要在写csv正文之前先:
var bom = System.Text.Encoding.UTF8.GetPreamble();
context.Response.BinaryWrite(bom);