我在一个 ASP.NET MVC 项目中集成jQuery.filer 时遇到了类似的问题。由于 jQuery.filer 在输入的名称属性末尾添加“[]”(即从文件到文件 []),我必须手动更改名称属性的值,如下所示:
$('#FileUpload').attr('name', 'FileUpload');
这是我通过 AJAX 在一些项目中使用的方法,并且工作没有任何问题。你可以试一试,让我知道它是否有效:
ViewModel:
[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." });
}
希望这会有所帮助...