[英]allow user to download dynamic csv file asp.net
I want to allow my user to click on a button that says "download" and then will build a dynamic csv file on the fly and will prompt the user to download. 我希望允许我的用户点击“下载”按钮,然后动态构建动态csv文件,并提示用户下载。 I know how to build the file using a HTTPHandler, but not quite sure the mechanism for delivering the content via download.
我知道如何使用HTTPHandler构建文件,但不太确定通过下载传递内容的机制。
I usually create a Generic Handler (.ashx) and do something like this: 我通常创建一个Generic Handler(.ashx)并执行以下操作:
public void ProcessRequest(HttpContext context)
{
StringBuilder myCsv = new StringBuilder();
foreach(myRow r in myRows) {
myCsv.AppendFormat("\"{0}\",{1}", r.MyCol1, r.MyCol2);
}
context.Response.ContentType = "application/csv";
context.Response.AddHeader("content-disposition", "attachment; filename=myfile.csv");
context.Response.Write(myCsv.ToString());
}
Now if the CSV you're building is REALLY big, you might want to write out each row as you create it, rather than stuffing it into a StringBuilder. 现在,如果您正在构建的CSV非常大,您可能希望在创建它时写出每一行,而不是将其填充到StringBuilder中。
Just emit a Content-Disposition
HTTP header in your HTTP Handler code. 只需在HTTP Handler代码中发出
Content-Disposition
HTTP标头。 Most browsers will interpret that as a download request. 大多数浏览器会将其解释为下载请求。 Replace
yourfile.csv
by the filename you want the user to see. 用您希望用户看到的文件名替换
yourfile.csv
。
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=yourfile.csv");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.