ASP.NET MVC ファイルダウンロード

ファイルダウンロード内容
  1. Views/Upload/Download.cshtmlでダウンロードボタンをクリック
  2. セッションにあるファイルをダウンロードする
作成物
  1. Views/Upload/Download.cshtmlを修正してダウンロードボタンを追加
  2. Controllers/DownloadsController.csを作成してセッションのストリームからファイルを戻す

コード

Views/Upload/Download.cshtml(修正)

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>ダウンロード</title>
</head>
<body>
    <div class="text-center">
        @* 追加 開始*@
        @using (Html.BeginForm("DownloadFile", "Downloads", FormMethod.Post))
        {
            <button type="submit">ダウンロード</button>
        }
        @* 追加 終了*@
    </div>
</body>
</html>
Controllers/Downloadscontroller.cs(新規)

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

namespace FileUploadDownload.Controllers
{
    public class DownloadsController : Controller
    {
        public IActionResult DownloadFile()
        {
            string contentType = "spplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            string fileName = HttpContext.Session.GetString("fileName");
            var stream = HttpContext.Session.Get("uploadedStream");
            HttpContext.Session.Clear();
            return File(stream, contentType, fileName);
        }
    }
}