jQuery Ajax文件上传到ASP.带有JSON响应的.NET web服务

本文关键字:响应 JSON NET 服务 web 带有 ASP 文件 Ajax jQuery | 更新日期: 2023-09-27 18:08:31

我正在尝试使用jQuery Ajax上传一个文件到c# Web服务(.asmx)。然后,该文件由Web Service处理,操作的结果异步返回给调用的JavaScript。

文件上传成功。但是,它要求在调用$.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<string>() { "No file uploaded." } };
        }
        else if (!new List<string>() { ".xls", ".xlsx" }.Contains(Path.GetExtension(HttpContext.Current.Request.Files[0].FileName).ToLower()))
        {
            Global.StructureSyncResult = new SyncResult() { Result = false, Log = new List<string>() { 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'上传文件。这样,响应将被序列化为JSON。我甚至可以访问文件作为WebMethod的参数,而不是使用HttpContext.Current.Request.Files
  • 或者找到一种方法强制WebService总是将返回值序列化为JSON,而不管客户端说什么。

任何想法?

提前感谢并致以亲切的问候,

克里斯。

jQuery Ajax文件上传到ASP.带有JSON响应的.NET web服务

您可以使用Ajax库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
    });
});
<html>
    <a id="button1"  style="width: 70%" class="button orange">Select File</a>
</html>

在服务器端,你可以写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;
            }  
        }
    }
}