2

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 using HttpContext.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.

1 Answer 1

1

You can use Ajax Library query.ajax_upload.0.6.js, this is simple to use.

My code is Just for hint !

Button1 is basically the button to select the file from File Selector dialog .

$(document).ready(function () {
    function  uploadFile(parameters) {
        /* example 1 */
        var button = $('#button1'), interval;
        $.ajax_upload(button, {
            action: "FileHandler.ashx?test=" + $("#paramter").val(),
            name: Selectedval,
            onSubmit: function (file, ext) {
                StartLoading();
            },
            onComplete: function (file, response) {                 
                StopLoading();                  
            }
        });
        uploadButton();//Register Event
    });
});

<html>
    <a id="button1"  style="width: 70%" class="button orange">Select File</a>
</html>

On Server Side, You can write httpFile handler;

public class FileHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //For multiple files
        foreach (string f in context.Request.Files.AllKeys)
        {
            HttpPostedFile file = context.Request.Files[f];
            if (!String.IsNullOrEmpty(file.FileName)) {
                string test = file.FileName;
            }  
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. While your solution may allow to return a JSON serialized result, it totally bypasses the web service. Can you think of a solution that does still involve the web service?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.