asp.net-mvc – 如何将名为“file []”的已发布数据绑定到MVC模型?

我使用 Redactor作为HTML编辑器,它有一个 component for uploading images and files.

Redactor负责客户端位,我需要提供服务器端上传功能.

如果我在控制器中使用Request.Files,我没有问题让上传工作.

但我想将发布的文件绑定到模型,我似乎无法做到这一点,因为它们发送的参数是files [] – 名称中带有方括号.

我的问题:

是否可以将发布的“file []”绑定到MVC模型?这是一个无效的属性名称,仅使用文件不起作用.

文件输入如下所示.我可以指定文件以外的名称,但Redactor会将[]添加到末尾,而不管名称如何.

<input type="file" name="file" multiple="multiple" style="display: none;">

我试图绑定到这样的属性

public HttpPostedFileBase[] File { get; set; }

当我看到上传发生时,我在请求中看到了这一点(我认为redactor可能会在幕后添加方括号):

Content-disposition: form-data; name="file[]"; filename="my-image.jpg"

也相关:

Redactor always sends the uploading request with content-type as multipart/form-data. So you don’t need to add this enctype anywhere

解决方法

您应该创建自定义模型绑定器以将上载的文件绑定到一个属性.
首先使用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);
    }
}

您还应该将binder提供程序添加到项目中,然后在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());

这不是一般解决方案,但我想你明白了.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....