ファイルダウンロード内容
- Views/Upload/Download.cshtmlでダウンロードボタンをクリック
- セッションにあるファイルをダウンロードする
作成物
- Views/Upload/Download.cshtmlを修正してダウンロードボタンを追加
- 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);
}
}
}