ASP.NET MVC5でFileアップロード機能をつくる場合、
実際のところ
Viewのところは、一般的なtype="file"で大丈夫です。
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
<!-- ... --!>
<label for="ImageUpload">Filename:</label>
<input type="file" name="ImageUpload" id="ImageUpload" />
<!-- ... --!>
}
該当ViewModelの方で
public class ViewModel { public string ImagePath{ get; set; } }
で、controllerの方で
// ...
using System.Web; // Server.MapPath()のために必要
// ....
public class UploadController : BaseController
{
public ActionResult UploadDocument()
{
return View();
}
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
var file = Request.Files["ImageUpload"];
if (file != null && file.ContentLength > 0){
var uploadDir = "~/uploads"
var imagePath = Path.Combine(Server.MapPath(uploadDir), file.FileName);
var imageUrl = Path.Combine(uploadDir, file.FileName);
file.SaveAs(imagePath);
model.ImagePath= imageUrl;
}
}
}
}