Note that there are some explanatory texts on larger screens.

plurals
  1. POHTML5, File API and jQuery posting image
    text
    copied!<p>I have a form that I show in a dialog, and it has a "submit" button that when clicked uses jQuery to post the form to the server using AJAX. This is to an MVC action method. The uploaded file was always null. Upon using Google, I read that you cannot normally post files using AJAX unless you use some sort of plugin.</p> <p>I did not wish to use a plugin and I read that this could be done with browsers that support the HTML5 File API, so I would like to get it working with this.</p> <p>I do not care about drag and drop or anything else at the moment, I only want to post up the file along with the rest of the form using jQuery.</p> <p>So far I have:</p> <p>This is the partial view for the form:</p> <pre><code>@model ImageReceiptLineModel @using (Html.BeginForm(MVC.EditImageReceiptLine(), FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.HiddenFor(model =&gt; model.ReceiptLineSetID) @Html.HiddenFor(model =&gt; model.LineNumber) &lt;input id="uploadFile" name="uploadFile" type="file" value="Choose New Image" /&gt; @Html.LabelFor(model =&gt; model.ImageDescription) @Html.TextBoxFor(model =&gt; model.ImageDescription) } </code></pre> <p>This is the jQuery for the sending of the form</p> <pre><code>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 } }); } </code></pre> <p>Here is the MVC action method:</p> <pre><code>/// &lt;summary&gt; /// Edit receipt line action /// &lt;/summary&gt; /// &lt;returns&gt;Action result&lt;/returns&gt; [HttpPost] public virtual ActionResult EditImageReceiptLine(HttpPostedFileBase uploadFile, ImageReceiptLineModel model) { } </code></pre> <p>What do I need to add to this to add the file to the form? "FormData" is the serialised form data that I post to the server.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload