[英]Using Response.TransmitFile to download file but also contains the page source
下面是有问题的代码,我下载了一个csv然而它将页面源附加到底部有关如何防止这种情况的任何想法?
var priceList = Test();
const string downloadName = "PriceList.csv";
var fs = new FileStream(downloadName, FileMode.Create);
var csv = new CsvHelper.CsvHelper(fs);
csv.Writer.WriteRecords(priceList);
Response.ClearContent();
//not sure what the correct content type is. This is probally wrong
Response.ContentType = "application/xls";
//Setting size is optional
Response.AddHeader("Content-Disposition",
"attachment; filename=" + downloadName + "; size=" + fs.Length.ToString());
var fn = fs.Name;
fs.Close();
loadingImage.Visible = false;
Response.TransmitFile(fn);
Response.Flush();
调用Response.End()
。
另外,为什么保存文件只是为了重新发送? 充其量这是浪费,但如果你重复使用这个名字,那么如果有两个人同时点击这个页面你会遇到竞争条件。 使用var csv = new CsvHelper.CsvHelper(Response.OutputStream)
而不是发送文件,所以你直接写入浏览器(你必须首先发送你的标题)。
此外,CSV文件的内容类型是text/csv
。
刷新流或尝试强制下载后添加Response.End()
方法。
var priceList = Test();
const string downloadName = "PriceList.csv";
var fs = new FileStream(downloadName, FileMode.Create);
var csv = new CsvHelper.CsvHelper(fs);
csv.Writer.WriteRecords(priceList);
Response.ClearContent();
//not sure what the correct content type is. This is probally wrong
Response.ContentType = "application/xls";
//Setting size is optional
Response.AddHeader("Content-Disposition",
"attachment; filename=" + downloadName + "; size=" + fs.Length.ToString());
var fn = fs.Name;
fs.Close();
loadingImage.Visible = false;
Response.TransmitFile(fn);
Response.Flush();
Response.End();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.