Cannot process jQuery AJAX FormData post for ASP.net 4 WebMethod web service.
<input id="ipt_file" type="file" /> <a href='#' onclick="UploadFile();" data-role='button'>Upload</a>
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" },
public class FileUploadRequest { public string job_id { get; set; } public string job_name { get; set; } public HttpPostedFile job_file { get; set; } }
[WebMethod] public string Upload(FileUploadRequest x) { string str_response = string.Empty; if (x.job_file.ContentLength > 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; }
You cannot correctly handle the parameter of a FormData object; here I created an instance of a custom class, but all I get back from the server is 500 errors (also tried a generic x object). Also tried to process it as an HttpRequest object, as I saw on some posts, but to no avail. Do not care about IE 9 incompatibility in this case; I just want to see the loading of a single file, or at least a FormData object with key / value pairs correctly accepted by WebMethod asmx.
source share