我使用Redactor作为HTML编辑器,它有一个component for uploading images and files。
Redactor负责客户端位,我需要提供服务器端上传功能。
如果我在控制器中使用Request.Files
,我上传工作没问题。
但我想将发布的文件绑定到模型,我似乎无法做到这一点,因为它们发送的参数是files[]
- 名称中带有方括号。
我的问题:
是否可以将发布的"file[]"
绑定到MVC模型?这是一个无效的属性名称,单独使用file
不起作用。
此文件输入如下所示。我可以指定除file
之外的名称,但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始终将内容类型的上传请求作为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);
}
}
您还应该将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());
这不是一般解决方案,但我想你明白了。
我在ASP.NET MVC项目中集成jQuery.filer时遇到了类似的问题。由于jQuery.filer将“[]”添加到输入的name属性的末尾(即从files到files []),我必须手动更改name属性的值,如下所示:
$('#FileUpload').attr('name', 'FileUpload');
这是我通过AJAX在一些项目中使用的方法,并且没有任何问题。你可以尝试一下,让我知道它是否有效:
视图模型:
[Display(Name = "Attachments")]
[DataType(DataType.Upload)]
public IEnumerable<HttpPostedFileBase> FileUpload { get; set; }
视图:
@model ViewModel
@using (Html.BeginForm("Insert", "Controller", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.FileUpload, new { type = "file", multiple = "multiple" })
<button id="btnSubmit" onclick="insert(event)" type="button">Save</button>
}
<script>
function insert(event) {
event.preventDefault();
//As jQuery.filer adds "[]" to the end of name attribute of input (i.e. from files to files[])
//we have to change the value of name attribute manually
$('#FileUpload').attr('name', 'FileUpload');
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '@Url.Action("Insert", "Cotroller")',
cache: false,
dataType: "json",
data: formdata,
/* If you are uploading files, then processData and contentType must be set
to falsein order for FormData to work (otherwise comment out both of them) */
processData: false,
contentType: false,
success: function (response, textStatus, XMLHttpRequest) {
//...
}
});
};
$(document).ready(function () {
$('#FileUpload').filer({
//code omitted for brevity
});
});
</script>
控制器:
public JsonResult Insert([Bind(Exclude = null)] ViewModel model)
{
if (ModelState.IsValid)
{
List<FileAttachment> fa = new List<FileAttachment>();
if (model.FileUpload != null)
{
FileAttachment fileAttachment = new FileAttachment //entity model
{
Created = DateTime.Now,
FileMimeType = upload.ContentType,
FileData = new byte[upload.ContentLength],
FileName = upload.FileName,
AuthorId = 1
};
upload.InputStream.Read(fileAttachment.FileData, 0, upload.ContentLength);
fa.Add(fileAttachment);
}
//code omitted for brevity
repository.SaveExperimentWithAttachment(model, fa);
return Json(new { success = true, message = "Record has been created." });
}
// If we got this far, something failed, redisplay form
return Json(new { success = false, message = "Please check the form and try again." });
}
希望这可以帮助...