I need to have a file upload on my view. To not mess with HttpPostedFileBase but rather to be able to use byte array for model binding I decided to extend ByteArrayModelBinder and implement it so that it automatically conerts HttpPostFileBase to byte[]. Here's how I did this:
public class CustomByteArrayModelBinder : ByteArrayModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var file = controllerContext.HttpContext.Request.Files[bindingContext.ModelName];
if (file != null)
{
if (file.ContentLength > 0)
{
var fileBytes = new byte[file.ContentLength];
file.InputStream.Read(fileBytes, 0, fileBytes.Length);
return fileBytes;
}
return null;
}
return base.BindModel(controllerContext, bindingContext);
}
}
protected void Application_Start()
{
...
ModelBinders.Binders.Remove(typeof(byte[]));
ModelBinders.Binders.Add(typeof(byte[]), new CustomByteArrayModelBinder());
}
After doing above I was supposed to be able to have a ViewModel like this:
public class Profile
{
public string Name {get; set;}
public int Age{get; set;}
public byte[] photo{get; set;}
}
In the view I create the corresponding html element like this:
@using (Html.BeginForm(null,null,FormMethod.Post,new { enctype = "multipart/form-data" })){
.........
@Html.TextBoxFor(x=>x.photo,new{type="file"})
<input type="submit" valaue="Save">
}
But when I submit the form I get the following 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.
In fact it's not my idea, I following th guide in this link. Don't know what to do because the execution stops at this line:
return base.BindModel(controllerContext, bindingContext);
Any ideas what to do?
EDIT: Controller action method:
[HttpPost]
public ActionResult Save(Profile profile){
if(ModelIsValid){
context.SaveProfile(profile);
}
}
But the action method is not even reached. The problem occurs prior to the action method.