LoginSignup
13
14

More than 5 years have passed since last update.

ASP.NET MVCでファイルをアップロードする

Last updated at Posted at 2014-08-25

ASP.NET MVCでのファイルのアップロードは、モデルバインダが対応している以外のサポートは無いようです。バインドする型としてHttpPostedFileWrapperクラスを指定するとそれがアップロードされたファイルの受け皿になります。

Upload.cshtml
@using (Html.BeginForm("UploadFile", null, FormMethod.Post, new { enctype="multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <input type="file" name="postedFile" />
    <input type="submit" value="アップロード" />
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadFile(HttpPostedFileWrapper postedFile)
{
    // postedFile.SaveAs()でファイルに保存するか
    // postedFile.InputStreamでストリームから内容を読み出して何かをする
    return new View(...);
}

アップロードされたファイルをLINQでデータベースに保存する場合は若干面倒です。
varbinary型のカラムはSystem.Data.Linq.Binaryにマッピングされますが、そのクラスにはbyte配列を取るコンストラクタしかなく、Streamの方にもbyte配列を取得するメソッドがありません。
とりあえず一度MemoryStreamにコピーしてからToArray()するのが最も簡単な方法のようです。

var memStream = new MemoryStream();
postedFile.inputStream.CopyTo(memStream);
var content = new System.Data.Linq.Binary(memStream.ToArray());
memStream.Dispose();

参考:

13
14
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
13
14