【问题标题】:PushStreamContent and ionic.zipPushStreamContent 和 ionic.zip
【发布时间】:2014-08-22 01:39:08
【问题描述】:

我的 webapi 即时压缩方法使用此代码

var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new PushStreamContent((stream, content, arg3) =>
                {
                    using (var zipEntry = new Ionic.Zip.ZipFile())
                    {
                        using (var ms = new MemoryStream())
                        {
                            _xmlRepository.GetInitialDataInXml(employee, ms);
                            zipEntry.AddEntry("content.xml", ms);
                            zipEntry.Save(stream); //process sleep on this line
                        }

                    }
                })
            };

            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "FromPC.zip"
            };
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue("application/octet-stream");


            return result;

我想要

1) 从 _xmlRepository.GetInitialDataInXml 获取数据

2) 通过 Ionic.Zip 动态压缩数据

3) 返回压缩流作为我的 WebApi 操作的输出

但是在这一行 zipEntry.Save(stream);执行过程停止并且不转到下一行。并且方法不返回任何东西

那么为什么它不返回我的文件?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api dotnetzip ionic-zip


    【解决方案1】:

    使用PushStreamContent 时,您需要close 流来表示您已完成对流的写入。

    Remarks 文档中的部分:
    http://msdn.microsoft.com/en-us/library/jj127066(v=vs.118).aspx

    【讨论】:

      【解决方案2】:

      接受的答案不正确。如果要开始流式传输,则无需关闭流式传输。当委派函数结束时,流式传输会自动开始(浏览器中的下载对话框)。如果抛出大文件 OutOfMemoryException ,但它会被处理并开始流式传输 -> HttResponseStream 被刷新到客户端。

      var result = new HttpResponseMessage(HttpStatusCode.OK);
      result.Content = new PushStreamContent(async (outputStream, httpContext, transportContext) =>
      {
          using (var zipStream = new ZipOutputStream(outputStream))
          {
              var employeeStream = _xmlRepository.GetEmployeeStream(); // PseudoCode
              zipStream.PutNextEntry("content.xml");
              await employeeStream.CopyToAsync(zipStream);
              outputStream.Flush();
          }
      });
      
      result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "FromPC.zip" };
      result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
      return result;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-16
        • 1970-01-01
        • 2018-10-08
        • 2016-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多