Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9360

【Razor Pages】BlobストレージからファイルをZip化してダウンロードする

$
0
0

Razor PagesでBlobストレージに格納したファイルを取得し、ZIPファイルとしてダウンロードさせるボタンを実装します。

実装する機能

  • クリック時にpostリクエストを実行するボタン
  • Blobストレージからファイルを取得
  • ファイルをZIP化してダウンロード

環境

  • .NET Core 3.1.9
  • Azure.Storage.Blobs 12.7.0
  • Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation 3.1.9

postリクエストを実行するボタン

asp-page-handlerでハンドラメソッドを指定します。

Index.cshtml
<formmethod="post"><inputasp-page-handler="Download"value="ダウンロード"type="submit"/></form>

OnPostDownloadで上記リクエストを受け取れます。
今回はDonwloadメソッドを実行するように実装します。

Index.cshtml.cs
publicasyncTask<IActionResult>OnPostDownload(){returnawaitDownload();}

Blobストレージからファイルを取得

今回はSAS URIでアクセスします。
ファイルを格納しているコンテナーのSAS URIを取得します。

  • SAS URI: http://xxxxx/xxxx
Index.cshtml.cs Download()
// SAS URIstringsasUri="http://xxxxx/xxxx";// ダウンロード対象のファイル名stringtargetFileName="testFile.txt";BlobContainerClientcontainerClient=newBlobContainerClient(newUri(sasUri),null);BlobClientblobClient=containerClient.GetBlobClient(targetFileName);BlobDownloadInfodownloadInfo=awaitblob.DownloadAsync();

ファイルをZIP化してダウンロード

メモリストリームでZIP化処理を実行します。

Index.cshtml.cs Download()
byte[]compressedBytes;using(varmemoryStream=newMemoryStream()){using(varzipArchive=newZipArchive(outStream,ZipArchiveMode.Create,true)){varentry=zipArchive.CreateEntry(targetFileName);using(vares=entry.Open()){//Blobストレージから取得したファイルをコピーawaitdownloadInfo.Content.CopyToAsync(es);}}compressedBytes=memoryStream.ToArray();}

Zip化したファイルをレスポンスとして返します。

Index.cshtml.cs Download()
stringzipName="test.zip";returnFile(compressedBytes,"application/zip",zipName);

まとめ

完成したソースコードです。

フォームのダウンロードボタン

Index.cshtml
<formmethod="post"><inputasp-page-handler="Download"value="ダウンロード"type="submit"/></form>

POSTのハンドラメソッド

Index.cshtml.cs OnPostDownload()
publicasyncTask<IActionResult>OnPostDownload(){returnawaitDownload();}

Downloadメソッド

2つのファイルを取得し、ZIP化するようにしました。

Index.cshtml.cs Download()
publicasyncTask<IActionResult>Download(){// SAS URIstringsasUri="http://xxxxx/xxxx";// ダウンロード対象のファイル名string[]targetFileNameList={"testFile1.txt","testFile2.txt"};BlobContainerClientcontainerClient=newBlobContainerClient(newUri(sasUri),null);byte[]compressedBytes;using(varmemoryStream=newMemoryStream()){using(varzipArchive=newZipArchive(outStream,ZipArchiveMode.Create,true)){foreach(vartargetFileNameintargetFileNameList){BlobClientblobClient=containerClient.GetBlobClient(targetFileName);varentry=zipArchive.CreateEntry(targetFileName);using(vares=entry.Open()){//Blobストレージから取得したファイルをコピーawaitdownloadInfo.Content.CopyToAsync(es);}}}compressedBytes=memoryStream.ToArray();}stringzipName="test.zip";returnFile(compressedBytes,"application/zip",zipName);}

参考記事


Viewing all articles
Browse latest Browse all 9360

Latest Images

Trending Articles