ユーザーがファイルをアップロードしてデータベースに保存できるように、フォームに機能を提供したいと考えています。これは ASP.NET MVC でどのように行われますか。
モデル クラスに書き込むデータ型。を試してみましByte[]
たが、スキャフォールディング中に、ソリューションは対応するビューで適切な HTML を生成できませんでした。
これらのケースはどのように処理されますか?
ユーザーがファイルをアップロードしてデータベースに保存できるように、フォームに機能を提供したいと考えています。これは ASP.NET MVC でどのように行われますか。
モデル クラスに書き込むデータ型。を試してみましByte[]
たが、スキャフォールディング中に、ソリューションは対応するビューで適切な HTML を生成できませんでした。
これらのケースはどのように処理されますか?
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>
}