且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HTML帮手<输入类型="文件" />

更新时间:2022-11-30 11:06:36

HTML文件上传ASP MVC 3。

型号:(注意FileExtensionsAttribute在MvcFutures可用它会验证文件扩展名的客户端和服务器端的)

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);
        }
    }
}