I am trying to upload a file using jQuery Ajax to a c# Web Service (.asmx). The file is then processed by the Web Service and the result of the operation is returned asynchronously to the calling JavaScript.
The file upload works. However, it requires that I omit the option contentType: 'application/json; charset=utf-8' when calling the $.ajax() function. And this causes the result not to be serialized as XML rather than the expected JSON. And this, in turn, causes jQuery to call the error handler instead of the success handler.
This is my client-side code:
$.ajax({
url: global.ajaxServiceUrl + '/StartStructureSynchronisation',
type: 'POST',
dataType: 'json',
//Ajax events
success: function (msg) {
// this handler is never called
error: function () {
// this handler is called even when the call returns HTTP 200 OK
},
data: data, // this is a valid FormData() object
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
And this is my server-side code:
[WebMethod(EnableSession = true)]
public string StartStructureSynchronisation()
{
return this.Execute(delegate
{
if (HttpContext.Current.Request.Files.Count == 0)
{
Global.StructureSyncResult = new SyncResult() { Result = false, Log = new List<string>() { "No file uploaded." } };
}
else if (!new List<string>() { ".xls", ".xlsx" }.Contains(Path.GetExtension(HttpContext.Current.Request.Files[0].FileName).ToLower()))
{
Global.StructureSyncResult = new SyncResult() { Result = false, Log = new List<string>() { String.Format("({0}) is not a valid Excel file.", HttpContext.Current.Request.Files[0].FileName) } };
}
else
{
Global.StructureSyncResult = new Synchronization().SyncStructure(HttpContext.Current.Request.Files[0].InputStream, ref Global.DocSyncCurrent, ref Global.DocSyncMax);
}
return Global.Serializer.Serialize(Global.StructureSyncResult);
});
}
So, basically, what I am looking for is one of two things:
- Either upload the file using
contentType: 'application/json; charset=utf-8'. That way, the response will be serialized as JSON. I could even access the file as a parameter of my WebMethod instead of usingHttpContext.Current.Request.Files. - Or find a way to force the WebService to always serialize the returned value as JSON, regardless of what the client says.
Any ideas?
Thanks a lot in advance and kind regards,
Chris.