Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle FormData AJAX post (file with additional params) with asp.net WebMethod
    text
    copied!<p>Having trouble handling a jQuery AJAX post of FormData to an ASP.net 4 Web service WebMethod.</p> <pre><code>&lt;input id="ipt_file" type="file" /&gt; &lt;a href='#' onclick="UploadFile();" data-role='button'&gt;Upload&lt;/a&gt; </code></pre> <hr> <pre><code>var UploadFile = function () { var file_object = $('#ipt_file')[0].files[0]; var form_data = new FormData(); form_data.append('job_id', '123456'); form_data.append('job_name', 'xyx'); form_data.append('job_file', file_object); var xhr_upload = $.ajax({ type: "POST", headers: { "Cache-Control":"no-cache", "Content-Type":"multipart/form-data" }, // also tried without these url: "../MyServices.asmx/Upload", data: form_data, processData: false, contentType: false, dataType: "json", success: function (msg) { if (typeof (msg) === "object") { var _upload = $.parseJSON(msg.d); alert(_upload.status + ': ' + _upload.msg); }; } }); }; </code></pre> <hr> <pre><code>public class FileUploadRequest { public string job_id { get; set; } public string job_name { get; set; } public HttpPostedFile job_file { get; set; } } </code></pre> <hr> <pre><code>[WebMethod] public string Upload(FileUploadRequest x) { string str_response = string.Empty; if (x.job_file.ContentLength &gt; 0) { str_response = "{\"status\":1,\"msg\":\"" + x.job_id + ", " + x.job_name + ", " + x.job_file.FileName + "\"}"; } else { str_response = "{\"status\":0,\"msg\":\"FAIL"\}"; }; return str_response; } </code></pre> <hr> <p>Must not be handling the FormData object parameter properly; here I instantiated a custom class, but all I get back from the server is 500 errors (also tried a generic object x). Also tried handling it as HttpRequest object as I've seen on some postings, to no avail. Not concerned about IE 9 incompatibility in this case; just want to see single file upload or at least a FormData object with key/value pairs properly received by an asmx WebMethod.</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