19

ユーザーがファイルをアップロードしてデータベースに保存できるように、フォームに機能を提供したいと考えています。これは ASP.NET MVC でどのように行われますか。

モデル クラスに書き込むデータ型。を試してみましByte[]たが、スキャフォールディング中に、ソリューションは対応するビューで適切な HTML を生成できませんでした。

これらのケースはどのように処理されますか?

4

1 に答える 1

44

byte[]モデルとHttpPostedFileBaseビューモデルで a を使用できます。例えば:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

その後:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        byte[] uploadedFile = new byte[model.File.InputStream.Length];
        model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length);

        // now you could pass the byte array to your model and store wherever 
        // you intended to store it

        return Content("Thanks for uploading the file");
    }
}

そして最後にあなたの見解で:

@model MyViewModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.LabelFor(x => x.File)
        @Html.TextBoxFor(x => x.File, new { type = "file" })
        @Html.ValidationMessageFor(x => x.File)
    </div>

    <button type="submit">Upload</button>
}
于 2013-02-27T07:31:58.650 に答える