Upload a file by posting a file in jquery ajax to an asmx

1.8k views Asked by At

I am trying to upload a file through a web service (ASMX)

I wrote the web service as following

[WebMethod]
public string UploadProducts(string Title, Stream documentStream)

I wrote a script in the client side as following

        var data = new FormData(),
        file = $("#fileUpload")[0].files[0]; // an input of type file
        if (file != null) {
            data.append("Title", "demotitle");
            data.append("documentStream", files[0]);
            $.ajax(
            {
                url: "FileManager.asmx/UploadFile",
                dataType: "json",
                type: "POST",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function () {alert('done') },
                error: function () { alert('error'); }
            });

This seems to be not working. Would be great if somebody can guide me where I am doing it wrong. Thanks in advance :)

1

There are 1 answers

0
Hassan Khan On

Remove dataType:json in your code.

var data = new FormData(),
file = $("#fileUpload")[0].files[0]; // an input of type file
if (file != null) {
    data.append("Title", "demotitle");
    data.append("documentStream", files[0]);
}
$.ajax(
{
    url: "FileManager.asmx/UploadFile",
    type: "POST",
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    success: function () {alert('done') },
    error: function () { alert('error'); }
});

This should work.