4

在将 FormData 的 jQuery AJAX 发布到 ASP.net 4 Web 服务 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;
}

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

4

2 回答 2

6

我确实让它与以下代码一起工作,以防有人想看到它:

    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 () {
        ...
    });
于 2014-10-09T14:37:45.310 回答
5

.NET 不允许内容类型使用multipart/form-data

JSON 劫持以及 ASP.NET AJAX 1.0 如何避免这些攻击

ASP.NET 对基于 GET 和 POST 的 ASP.NET AJAX Web 方法强制执行了一个内置的保护验证层,即无论使用什么 HTTP 动词,A SP.NET 始终要求 HTTP Content-类型标头设置为值 application/json。如果不发送此内容类型标头,ASP.NET AJAX 将拒绝服务器上的请求。

于 2014-10-09T08:22:45.703 回答