jQuery Ajax文件使用JSON响应上载到ASP.NET Web服务

我正在尝试使用jQuery Ajax将文件上传到ac#Web Service(.asmx)。 然后,Web Service处理该文件,并将操作结果异步返回给调用JavaScript。

文件上传有效。 但是,它要求我省略选项contentType: 'application/json; charset=utf-8' 调用$.ajax()函数时contentType: 'application/json; charset=utf-8' 。 这导致结果不能序列化为XML而不是预期的JSON。 反过来,这会导致jQuery调用error处理程序而不是success处理程序。

这是我的客户端代码:

 $.ajax({ url: global.ajaxServiceUrl + '/StartStructureSynchronisation', type: 'POST', dataType: 'json', //Ajax events success: function (msg) { // this handler is never called error: function () { // this handler is called even when the call returns HTTP 200 OK }, data: data, // this is a valid FormData() object //Options to tell jQuery not to process data or worry about content-type. cache: false, contentType: false, processData: false }); 

这是我的服务器端代码:

 [WebMethod(EnableSession = true)] public string StartStructureSynchronisation() { return this.Execute(delegate { if (HttpContext.Current.Request.Files.Count == 0) { Global.StructureSyncResult = new SyncResult() { Result = false, Log = new List() { "No file uploaded." } }; } else if (!new List() { ".xls", ".xlsx" }.Contains(Path.GetExtension(HttpContext.Current.Request.Files[0].FileName).ToLower())) { Global.StructureSyncResult = new SyncResult() { Result = false, Log = new List() { String.Format("({0}) is not a valid Excel file.", HttpContext.Current.Request.Files[0].FileName) } }; } else { Global.StructureSyncResult = new Synchronization().SyncStructure(HttpContext.Current.Request.Files[0].InputStream, ref Global.DocSyncCurrent, ref Global.DocSyncMax); } return Global.Serializer.Serialize(Global.StructureSyncResult); }); } 

所以,基本上,我要找的是两件事之一:

  • 使用contentType: 'application/json; charset=utf-8'上传文件contentType: 'application/json; charset=utf-8' contentType: 'application/json; charset=utf-8' 。 这样,响应将被序列化为JSON。 我甚至可以访问该文件作为我的WebMethod的参数,而不是使用HttpContext.Current.Request.Files
  • 或者找到一种方法来强制WebService始终将返回的值序列化为JSON,无论客户端说什么。

有任何想法吗?

非常感谢提前和亲切的问候,

克里斯。

您可以使用Ajax Library query.ajax_upload.0.6.js ,这很容易使用。

我的代码只是提示!

Button1基本上是从“文件选择器”对话框中选择文件的按钮。

 $(document).ready(function () { function uploadFile(parameters) { /* example 1 */ var button = $('#button1'), interval; $.ajax_upload(button, { action: "FileHandler.ashx?test=" + $("#paramter").val(), name: Selectedval, onSubmit: function (file, ext) { StartLoading(); }, onComplete: function (file, response) { StopLoading(); } }); uploadButton();//Register Event }); });  Select File  

在服务器端,您可以编写httpFile处理程序;

 public class FileHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { //For multiple files foreach (string f in context.Request.Files.AllKeys) { HttpPostedFile file = context.Request.Files[f]; if (!String.IsNullOrEmpty(file.FileName)) { string test = file.FileName; } } } }