繁体   English   中英

PushStreamContent和ionic.zip

[英]PushStreamContent and ionic.zip

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

那为什么不返回文件呢?

使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM