11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FileResultでzipファイルを返す

11
Last updated at Posted at 2014-05-15

目的

複数のcsvファイルをzipにまとめてダウンロードするやり方のメモ。

準備

DotNetZipを使用します。(中身のIonic.Zip.dllを使用)
NuGetで追加するのが簡単だと思います。

コード


public ActionResult DownloadZip(){
    var csv1 = "hoge,moge,piyo";
    var csv2 = "foo,bar";

    var zip = new Ionic.Zip.ZipFile();

    zip.AddEntry("csv1.csv", Encoding.GetEncoding("Shift_JIS").GetBytes(csv1));
    zip.AddEntry("csv2.csv", Encoding.GetEncoding("Shift_JIS").GetBytes(csv2));

    var ms = new MemoryStream();
    zip.Save(ms);
    ms.Position = 0;

    return File(ms, System.Net.Mime.MediaTypeNames.Application.Zip, "FileName.zip");
}

まとめ

ZipFileインスタンスを作ってファイル名とbyte配列を追加していき、MemoryStreamに格納してFileResultで返すという流れです。
当然csv以外のファイルも可能。

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?