Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle FormData AJAX post (file with additional params) with asp.net WebMethod

Having trouble handling a jQuery AJAX post of FormData to an ASP.net 4 Web service WebMethod.

<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" }, // 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);
            };
        }
    });
};

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;
}

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.

like image 971
brnwdrng Avatar asked Dec 21 '22 02:12

brnwdrng


2 Answers

I did get it to work with the following code, in case anyone wants to see it:

    var upload_file = $('#ipt_file')[0].files[0];
    var upload_filename = upload_file.name;
    var upload_maxsize = 10485760;
    var upload_projectname = "test";
    var form_data = new FormData();
    form_data.append('session_id', this.sessionID());
    form_data.append('project_name', upload_projectname);
    form_data.append('file_name', upload_filename);
    form_data.append('file_size', upload_file.size);
    form_data.append('file', upload_file);
    if (upload_file.size < upload_maxsize) {
    var xhr_upload = $.ajax({
        type: "POST",
        headers: { 'Cache-Control': 'no-cache' },
        url: "../services/upload.ashx",
        data: form_data,
        processData: false,
        contentType: false,
        dataType: "json"
        }
    })
    .done(function (xhr_data) {
        ...
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        ...
    })
    .always(function () {
        ...
    });
like image 155
brnwdrng Avatar answered Dec 28 '22 12:12

brnwdrng


.NET will not allow the multipart/form-data for the content-type:

JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks

There is a built-in validation layer of protection that ASP.NET enforces for both GET and POST based ASP.NET AJAX web methods, which is that regardless of the HTTP verb being used, ASP.NET always requires that the HTTP Content-Type header is set to the value application/json. It this content type header is not sent, ASP.NET AJAX will reject the request on the server.

like image 24
benedict_w Avatar answered Dec 28 '22 12:12

benedict_w