1

我用于即时压缩的 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); 执行过程停止并且不转到下一行。并且方法不返回任何东西

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

4

2 回答 2

1

使用时PushStreamContent,您需要向close流发出信号,表明您已完成向流的写入。

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

于 2014-07-01T15:53:02.713 回答
1

接受的答案不正确。如果要开始流式传输,则无需关闭流。当委托功能结束时,流式传输会自动开始(浏览器中的下载对话框)。如果抛出大文件 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;
于 2017-03-14T10:35:06.323 回答