使用asp.net Web表单中的流返回可下载文件 [英] Returning a downloadable file using a stream in asp.net web forms
本文介绍了使用asp.net Web表单中的流返回可下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在asp.net MVC中,我可以执行以下操作来打开流:
In asp.net MVC I can do something like the following which will open a stream:
Stream strm1 = GenerateReport(Id);
return File(strm1,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Report_" + reportId.ToString() + ".xlsx");
请注意我如何传递作为流的strm1.然后可以将其命名为Report_ + ... xlsx,如上面的示例所示.
Notice how I am passing strm1 which is a stream. I can then name it Report_+ ...xlsx like the example above shows.
是否有使用c#使用asp.net Web表单执行此操作的类似方法.
Is there a similar way to do this with asp.net web forms using c#.
推荐答案
您可以使用 WriteFile (如果该文件位于您的网站文件夹中).
You can use TransmitFile or WriteFile if the file is in your website folder.
string fileName = string.Format("Report_{0}.xlsx", reportId);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition",
string.Format("attachment; filename={0}", fileName));
Response.TransmitFile(fileName);
Response.End();
流
如果您的数据已经在内存中,则需要此方法以大块形式写入响应.
Stream
If your data is already in Memory, you want this method which writes the response in chunks.
Stream stm1 = GenerateReport(Id);
Int16 bufferSize = 1024;
byte[] buffer = new byte[bufferSize + 1];
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition",
string.Format("attachment; filename=\"Report_{0}.xlsx\";", reportId));
Response.BufferOutput = false;
int count = stm1.Read(buffer, 0, bufferSize);
while (count > 0)
{
Response.OutputStream.Write(buffer, 0, count);
count = stm1.Read(buffer, 0, bufferSize);
}
这篇关于使用asp.net Web表单中的流返回可下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文