下载管理器启动后,HttpContext.Current.Response写入文件

时间:2010-12-17 20:54:38

标签: c# asp.net performance httpresponse

我正在尝试动态创建一个ZIP文件,其中可能包含数千张图片。

    public static void CompressAndSendFiles(List files)     {         HttpContext.Current.Response.ClearContent();

    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"Jpeg Package " 
                                            + DateTime.Now.ToString("MM-dd-yyyy hh-mm-ss") + ".zip\"");

    // Add the file size into the response header
    //HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());

    // Set the ContentType
    HttpContext.Current.Response.ContentType = ReturnHttpContentType("download.zip");

    ZipOutputStream oZipStream = 
                   new ZipOutputStream(HttpContext.Current.Response.OutputStream);

    try
    {
        foreach (string file in files)
        {


            FileInfo fInfo = new FileInfo(file);
            ZipEntry oZipEntry = new ZipEntry(fInfo.Name);
            oZipStream.PutNextEntry(oZipEntry);
            byte[] buffer = File.ReadAllBytes(file);
            oZipStream.Write(buffer, 0, buffer.Length);

            //oZipStream.Flush();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        oZipStream.Finish();
        oZipStream.Close();
        oZipStream.Dispose();

     }
     HttpContext.Current.Response.OutputStream.Flush();
     HttpContext.Current.Response.End();
}

一切都很好,除非文件数量变大。

我的问题: 有没有办法启动下载(让客户端下载管理器弹出),然后开始在流上写?

我监控了w3wp.exe(IIS)进程,似乎数据正在写入内存而不是Stream。当w3wp.exe内存使用量增加一定数量时,它会释放内存并且没有任何反应(没有下载)。

提前谢谢。

2 个答案:

答案 0 :(得分:2)

您是否尝试过使用此功能?

HttpContext.Current.Response.BufferOutput = false;

答案 1 :(得分:1)

据我所知,您无法在归档时对其进行流式传输。您需要先将它们压缩,然后再流式传输。结果,如果最终的zip非常大,服务器最终会内存不足。

我最终做的是将其写入临时zip文件,然后流式传输该临时文件。