好的,我已經把我的頭髮拉了這麼久了。我有一個WebService向瀏覽器發送一個zip文件。這有效;當我測試WebService並直接通過它調用方法時,zip文件就會正確地下載到瀏覽器中。通過回覆發送Zip文件給客戶端 - 發送的類型不正確
當我使用jQuery向WebService發送AJAX請求時,問題就出現了 - zip文件被下載到響應中,但它保留在響應中並且不作爲文件下載。
這裏是我的代碼:
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=pleasework.zip");
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory("c:\\inetpub\\mediaserver\\music\\mixes");
zip.AddFile("c:\\test.txt");
zip.AddFile("c:\\test2.txt");
zip.Save("c:\\filename.zip");
}
HttpContext.Current.Response.TransmitFile("c:\\iloveshrooms.zip");
return "done";
}
現在這個工作,因爲該文件下載時,我直接導航到該服務時使用「調用」功能。
這裏是我的jQuery AJAX請求......
function getFile() {
alert("sending POST request...");
$.ajax({
type: 'POST',
url: 'ZipService.asmx/GetZipFile HTTP 1.1',
contentType: "application/x-www-form-urlencoded",
data: '{ "path":"c:\\inetpub\\mediaserver\\music\\mixes" }',
dataType: '',
beforeSend: function(xhr) {xhr.setRequestHeader("Accept","application/zip");},
success: function() {alert(":-)");},
failure: function() {alert(":-(");}
});
}
我加入了代碼「beforeSend」,這樣的請求表明明確的瀏覽器應該期待什麼樣的反應。
我一直在使用Firebug來監視請求/響應標題,並且看不到任何錯誤(除了當我查看響應的內容時,它充滿了二進制數據並且其大小與文件我送。
我只是嘗試上傳的請求/響應頭和效應初探內容的屏幕轉儲,但我沒有足夠的聲譽分,要做到這一點還沒有:-(
Response是Zip文件的大小,所以我假設它被髮送回瀏覽器,但瀏覽器不知道該如何處理。
經過IE測試,FF和Chrome & Chrome的結果是一致的。
如果有人可以擺脫這種情況,我會非常感激!