【发布时间】:2014-07-21 16:23:24
【问题描述】:
我需要在我的视图上上传文件。为了不弄乱 HttpPostedFileBase,而是为了能够使用字节数组进行模型绑定,我决定扩展 ByteArrayModelBinder 并实现它,以便它自动将 HttpPostFileBase 连接到 byte[]。我是这样做的:
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());
}
完成上述操作后,我应该能够拥有这样的 ViewModel:
public class Profile
{
public string Name {get; set;}
public int Age{get; set;}
public byte[] photo{get; set;}
}
在视图中,我像这样创建相应的 html 元素:
@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">
}
但是当我提交表单时,我收到以下错误:
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.
事实上这不是我的主意,我遵循this link 中的指南。不知道该怎么办,因为执行在这一行停止:
return base.BindModel(controllerContext, bindingContext);
有什么想法吗?
编辑:控制器操作方法:
[HttpPost]
public ActionResult Save(Profile profile){
if(ModelIsValid){
context.SaveProfile(profile);
}
}
但是甚至没有达到动作方法。问题出现在action方法之前。
【问题讨论】:
-
你能发布你的控制器操作方法吗?
-
@Overmachine,请看编辑,我已经添加了动作方法。但是错误发生在操作方法之前。
-
我刚刚测试了 linl 上的代码,一切正常,我唯一想到的是您提供的 html 上的拼写错误:/ 就像 @Html.TextBox|For 应该是 @ TextBoxFor()
标签: asp.net-mvc-4 bytearray model-binding httppostedfilebase