将MemoryStream写入响应对象

Ali*_*Ali 37 c# asp.net httpresponse

我正在使用以下代码来流式传输一个MemoryStream对象中的pptx,但是当我打开它时,我在PowerPoint中获得了修复消息,将MemoryStream写入响应对象的正确方法是什么?

HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pptx;", getLegalFileName(CurrentPresentation.Presentation_NM)));                
response.BinaryWrite(masterPresentation.ToArray());
response.End();
Run Code Online (Sandbox Code Playgroud)

pla*_*ful 65

我有同样的问题,唯一有效的解决方案是:

Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
Response.BinaryWrite(myMemoryStream.ToArray());
// myMemoryStream.WriteTo(Response.OutputStream); //works too
Response.Flush();
Response.Close();
Response.End();
Run Code Online (Sandbox Code Playgroud)

  • 根据[这篇文章](https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response.end,-response.redirect,-or-server .transfer) `Response.End()` 抛出一个异常,这并不是你真正想要的。使用`HttpContext.Current.ApplicationInstance.CompleteRequest();` (3认同)

Ian*_*son 12

假设你可以获得Stream,FileStream或MemoryStream,你可以这样做:

Stream file = [Some Code that Gets you a stream];
var filename = [The name of the file you want to user to download/see];

if (file != null && file.CanRead)
{
    context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    context.Response.ContentType = "application/octet-stream";
    context.Response.ClearContent();
    file.CopyTo(context.Response.OutputStream);
}
Run Code Online (Sandbox Code Playgroud)

这是我的一些工作代码的复制和粘贴,因此内容类型可能不是您要查找的内容,但是将流写入响应是最后一行的技巧.


Dar*_*rov 7

而不是在MemoryStream中创建PowerPoint演示文稿,而是直接将其写入Response.OutputStream.这样您就不需要在服务器上浪费任何内存,因为组件将直接将输出流式传输到网络套接字流.因此,不是将MemoryStream传递给生成此演示文稿的函数,而只是传递Response.OutputStream.