PushStreamContent and ionic.zip

本文关键字:zip ionic and PushStreamContent | 更新日期: 2023-09-27 18:10:54

我的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;

I want to

1)从_xmlRepository获取数据。GetInitialDataInXml

2)通过Ionic.Zip压缩数据

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

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

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

PushStreamContent and ionic.zip

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

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

接受的答案不正确。如果要开始流式传输,则不需要关闭流。当委托函数结束时,流自动开始(在浏览器中下载对话框)。在大文件的情况下抛出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;