public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv",
ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
public HttpPostedFileBase File { get; set; }
}
HTML 查看 :
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.File)
}
控制器操作 :
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
}
public class ViewModel
{
public HttpPostedFileBase File{ get; set; }
}
观看内容:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
}
控制器动作:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
var postedFile = Request.Files["File"];
// now you can get and validate the file type:
var isFileSupported= IsFileSupported(postedFile);
}
}
public bool IsFileSupported(HttpPostedFileBase file)
{
var isSupported = false;
switch (file.ContentType)
{
case ("image/gif"):
isSupported = true;
break;
case ("image/jpeg"):
isSupported = true;
break;
case ("image/png"):
isSupported = true;
break;
case ("audio/mp3"):
isSupported = true;
break;
case ("audio/wav"):
isSupported = true;
break;
}
return isSupported;
}