我在用Redactor作为一个 HTML 编辑器,它有一个用于上传图像和文件的组件.
Redactor 负责客户端部分,我需要提供服务器端上传功能。
如果我使用的话,上传工作没有问题Request.Files
在控制器中。
但我想将发布的文件绑定到模型,但我似乎无法做到这一点,因为它们发送的参数是files[]
- 名称中带有方括号。
我的问题:
发帖的可以绑定吗"file[]"
到 MVC 模型?这是一个无效的属性名称,并且使用file
单独是行不通的。
该文件输入看起来像这样。我可以指定一个名称以外的名称file
,但编辑器添加[]
到最后,无论名字如何。
<input type="file" name="file" multiple="multiple" style="display: none;">
我正在尝试绑定到这样的属性:
public HttpPostedFileBase[] File { get; set; }
当我观看上传时,我在请求中看到了这一点(我认为编辑器可能在幕后添加了方括号):
Content-Disposition: form-data; name="file[]"; filename="my-image.jpg"
还相关:
Redactor 始终发送内容类型为 multipart/form-data 的上传请求。所以你不需要在任何地方添加这个 enctype
您应该创建一个自定义模型绑定器以将上传的文件绑定到一个属性。
首先创建一个模型HttpPostedFileBase[]
财产
public class RactorModel
{
public HttpPostedFileBase[] Files { get; set; }
}
然后实施DefaultModelBinder
并覆盖BindProperty
public class RactorModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
int len = controllerContext.HttpContext.Request.Files.AllKeys.Length;
if (len > 0)
{
if (propertyDescriptor.PropertyType == typeof(HttpPostedFileBase[]))
{
string formName = string.Format("{0}[]", propertyDescriptor.Name);
HttpPostedFileBase[] files = new HttpPostedFileBase[len];
for (int i = 0; i < len; i++)
{
files[i] = controllerContext.HttpContext.Request.Files[i];
}
propertyDescriptor.SetValue(bindingContext.Model, files);
return;
}
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
另外,您应该将活页夹提供程序添加到您的项目中,然后在 global.asax 中注册它
public class RactorModenBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
if (modelType == typeof(RactorModel))
{
return new RactorModelBinder();
}
return null;
}
}
...
ModelBinderProviders.BinderProviders.Insert(0, new RactorModenBinderProvider());
这不是一个通用的解决方案,但我想你明白了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)