2
我想上傳一個文件使用jQuery Ajax到C#Web服務(.asmx)。該文件然後由Web服務處理,並且該操作的結果異步返回到調用JavaScript。jQuery Ajax文件上傳到ASP.NET Web服務與JSON響應
文件上傳工作。但是,它要求在調用$.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,而不管客戶說什麼。
任何想法?
在此先感謝和親切的問候,
Chris。
謝謝你的回答。儘管您的解決方案可能允許返回JSON序列化結果,但它完全繞過了Web服務。你能想到一個仍然涉及Web服務的解決方案嗎? – Christophe