[英]jQuery Ajax File Upload to ASP.NET web service with JSON response
我正在嘗試使用jQuery Ajax將文件上傳到ac#Web服務(.asmx)。 然后,該文件由Web服務處理,並且操作結果異步返回到調用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<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'
上傳文件contentType: 'application/json; charset=utf-8'
contentType: 'application/json; charset=utf-8'
。 這樣,響應將被序列化為JSON。 我什至可以將文件作為WebMethod的參數來訪問,而不是使用HttpContext.Current.Request.Files
。 有任何想法嗎?
在此先感謝您,也謝謝您,
克里斯。
您可以使用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;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.