Html helper for <input type=“file” />

后端 未结 8 2037
予麋鹿
予麋鹿 2020-11-28 18:16

Is there a HTMLHelper for file upload? Specifically, I am looking for a replace of


using ASP.NET

8条回答
  •  悲哀的现实
    2020-11-28 19:07

    HTML Upload File ASP MVC 3.

    Model: (Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.)

    public class ViewModel
    {
        [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv", 
                 ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
        public HttpPostedFileBase File { get; set; }
    }
    

    HTML View:

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

    Controller action:

    [HttpPost]
    public ActionResult Action(ViewModel model)
    {
        if (ModelState.IsValid)
        {
            // Use your file here
            using (MemoryStream memoryStream = new MemoryStream())
            {
                model.File.InputStream.CopyTo(memoryStream);
            }
        }
    }
    

提交回复
热议问题