在将 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 正确接收。