HTML5,File API和jQuery发布图片

我有一个表单,我在一个对话框中显示,它有一个“提交”按钮,单击时使用jQuery使用AJAX将表单发布到服务器。 这是一个MVC动作方法。 上传的文件始终为null。 在使用谷歌时,我读到你通常不能使用AJAX发布文件,除非你使用某种插件。

我不想使用插件,我读到这可以通过支持HTML5文件API的浏览器来完成,所以我想让它使用它。

我不关心拖放或其他任何东西,我只想使用jQuery将文件与表单的其余部分一起发布。

到目前为止我有:

这是表单的部分视图:

@model ImageReceiptLineModel @using (Html.BeginForm(MVC.EditImageReceiptLine(), FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.HiddenFor(model => model.ReceiptLineSetID) @Html.HiddenFor(model => model.LineNumber)  @Html.LabelFor(model => model.ImageDescription) @Html.TextBoxFor(model => model.ImageDescription) } 

这是用于发送表单的jQuery

 if ($Form.valid()) { // get the url and the form data to send the request var Url = $Form.attr('action'); var FormData = $Form.serialize(); // now do the ajax call $.ajax({ url: Url, data: FormData, type: 'POST', cache: 'false', success: function (data, textStatus, jqXHR) { // do something here }, error: function (jqXHR, textStatus, errorThrown) { // do something here } }); } 

这是MVC动作方法:

 ///  /// Edit receipt line action ///  /// Action result [HttpPost] public virtual ActionResult EditImageReceiptLine(HttpPostedFileBase uploadFile, ImageReceiptLineModel model) { } 

我需要添加什么才能将文件添加到表单中? “FormData”是我发布到服务器的序列化表单数据。

以下是有关可用于上传文件的File API的guide 。 但是不要忘记这对IE9不起作用。 如果您需要支持此类浏览器,可以使用隐藏的iframe来模拟使用AJAX上传文件。 这就是为什么存在jquery.form等插件的原因。 为了使它成为一行代码,您不必担心浏览器支持和内容:

 if ($Form.valid()) { // get the url and the form data to send the request $Form.ajaxSubmit({ success: function (data, textStatus, jqXHR) { // do something here }, error: function (jqXHR, textStatus, errorThrown) { // do something here } }); } 

更新:

根据评论部分的要求,您可以使用File API。

我们假设你有以下forms:

 @using (Html.BeginForm(MVC.EditImageReceiptLine(), null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.HiddenFor(model => model.ReceiptLineSetID) @Html.HiddenFor(model => model.LineNumber)  @Html.LabelFor(model => model.ImageDescription) @Html.TextBoxFor(model => model.ImageDescription) } 

以及一些会触发表单提交的链接:

 Upload the file using HTML5 File API 

现在在js文件中,您可以拥有以下内容:

 $('#upload').click(function () { if (!window.FileReader) { // the browser doesn't support the File API - there's no need // to continue; alert('To use this functionality please use a modern browser'); return; } var $form = $('form'); var uri = $form.action; var xhr = new XMLHttpRequest(); var fd = new FormData(); $form.find(':input').each(function () { if ($(this).is('input[type="file"]')) { var files = $(this)[0].files; if (files.length > 0) { fd.append(this.name, files[0]); } } else { fd.append(this.name, $(this).val()); } }); xhr.open('POST', uri, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { // handle response. alert(xhr.responseText); } }; xhr.send(fd); });