有人设法让默认活页夹与输入文件控件和字节数组类型的属性一起使用吗?
如果我的 ViewModel 上有一个名为 Image 的属性,并且我的视图名称 Image 上有一个文件输入控件,则默认活页夹会发出此错误:
输入不是有效的 Base-64 字符串,因为它包含非 base-64 字符、两个以上的填充字符或填充字符中的非空白字符。
有人设法让默认活页夹与输入文件控件和字节数组类型的属性一起使用吗?
如果我的 ViewModel 上有一个名为 Image 的属性,并且我的视图名称 Image 上有一个文件输入控件,则默认活页夹会发出此错误:
输入不是有效的 Base-64 字符串,因为它包含非 base-64 字符、两个以上的填充字符或填充字符中的非空白字符。
为什么需要byte[]
数组?默认模型绑定器适用于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" />
<% } %>
以及将处理此问题的控制器操作:
[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");
}
这也适用于多个文件。您只需IEnumerable<HttpPostedFileBase>
在动作方法的签名中使用。
您应该创建一个自定义模型绑定器,将您上传的文件直接关联到模型中的 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);
}
}
您还必须删除默认模型绑定器,并添加您的(在 Global.asax.cs 中,在 Application_Start 方法中):
ModelBinders.Binders.Remove(typeof(byte[]));
ModelBinders.Binders.Add(typeof(byte[]), new CustomByteArrayModelBinder());
此代码已从这篇好文章中退休:http: //prideparrot.com/blog/archive/2012/6/model_binding_posted_file_to_byte_array
最好的祝福 :)