12

ユーザーがサイトからすべての画像をダウンロードできるように、簡単なダウンロードサービスを作成しています。これを行うには、すべてを http ストリームに圧縮します。

ただし、すべてがメモリに保存されているようで、zip ファイルが完成して出力が閉じられるまでデータは送信されません。サービスがすぐに送信を開始し、メモリを使いすぎないようにしたい。

public void ProcessRequest(HttpContext context)
{
    List<string> fileNames = GetFileNames();
    context.Response.ContentType = "application/x-zip-compressed";
    context.Response.AppendHeader("content-disposition", "attachment; filename=files.zip");
    context.Response.ContentEncoding = Encoding.Default;
    context.Response.Charset = "";

    byte[] buffer = new byte[1024 * 8];

    using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutput = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream))
    {
        foreach (string fileName in fileNames)
        {
            ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
            zipOutput.PutNextEntry(zipEntry);
            using (var fread = System.IO.File.OpenRead(fileName))
            {
                ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fread, zipOutput, buffer);
            }
        }
        zipOutput.Finish();
    }

    context.Response.Flush();
    context.Response.End();
}

ファイルの作成中にワーカープロセスのメモリが増加し、送信が完了するとメモリが解放されることがわかります。メモリをあまり使用せずにこれを行うにはどうすればよいですか?

4

3 に答える 3

11

で応答バッファリングを無効にし、コードの最後から呼び出しcontext.Response.BufferOutput = false;を削除します。Flush

于 2009-03-09T13:23:04.027 に答える
0

ご参考までに。これは、ブラウザーへのストリーミングを使用して、ファイルのツリー全体を再帰的に追加する作業コードです。

string path = @"c:\files";

Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", "hive.zip"));
Response.BufferOutput = false;

byte[] buffer = new byte[1024 * 1024];
using (ZipOutputStream zo = new ZipOutputStream(Response.OutputStream, 1024 * 1024)) {
    zo.SetLevel(0);
    DirectoryInfo di = new DirectoryInfo(path);
    foreach (string file in Directory.GetFiles(di.FullName, "*.*", SearchOption.AllDirectories)) {
        string folder = Path.GetDirectoryName(file);
        if (folder.Length > di.FullName.Length) {
            folder = folder.Substring(di.FullName.Length).Trim('\\') + @"\";
        } else {
            folder = string.Empty;
        }
        zo.PutNextEntry(new ZipEntry(folder + Path.GetFileName(file)));
        using (FileStream fs = File.OpenRead(file)) {
            ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fs, zo, buffer);
        }
        zo.Flush();
        Response.Flush();
    }
    zo.Finish();
}

Response.Flush();
于 2010-08-09T09:26:08.127 に答える
0

Response.BufferOutput = false; を使用します。ProcessRequest の開始時に、各ファイルの後に応答をフラッシュします。

于 2009-03-09T13:25:14.877 に答える