asp.net-mvcmodelbindersdefaultmodelbinder

Input file autobind to byte[] array in ASP.NET MVC


Anyone managed to get default binder to work with input file control and property of type byte array?

If I have a property on my ViewModel named Image and a file input control on my view name Image, default binder issue this error:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.


Solution

  • Why do you need a byte[] array? The default model binder works with HttpPostedFileBase:

    <% using (Html.BeginForm("upload", "home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
        <input type="file" name="file" id="file" />
        <input type="submit" value="Upload" />
    <% } %>
    

    And the controller action that will handle this:

    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        if (file.ContentLength > 0) 
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
            file.SaveAs(path);
        }
        return RedirectToAction("Index");
    }
    

    This works also with multiple files. You simply use IEnumerable<HttpPostedFileBase> in the signature of the action method.