如何使用asp.net WebMethod处理FormData AJAX帖子(带有附加参数的文件)

前端之家收集整理的这篇文章主要介绍了如何使用asp.net WebMethod处理FormData AJAX帖子(带有附加参数的文件)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

无法将FormData的jQuery AJAX帖子处理到ASP.net 4 Web服务WebMethod.

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

不能正确处理FormData对象参数;在这里我实例化了一个自定义类,但是我从服务器返回的所有内容都是500个错误(也尝试了一个通用对象x).还尝试将其作为HttpRequest对象处理,就像我在一些帖子中看到的那样,无济于事.在这种情况下不关心IE 9的不兼容性;只想查看单个文件上传或至少一个具有由asmx WebMethod正确接收的键/值对的FormData对象.

最佳答案
我确实让它使用以下代码,以防有人想看到它:

    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",dataType: "json"
        }
    })
    .done(function (xhr_data) {
        ...
    })
    .fail(function (jqXHR,textStatus,errorThrown) {
        ...
    })
    .always(function () {
        ...
    });
原文链接:https://www.f2er.com/jquery/428714.html

猜你在找的jQuery相关文章