1
我有這個功能,它實際上文件下載(在一個名爲AzureTest的控制器中);它的一個MVC項目:Azure blob下載時使用ajax不在MVC項目中工作
private bool DownloadKit()
{
bool bReturn, bSuccess = false;
CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("ConnString");
CloudBlobClient cbcClient = account.CreateCloudBlobClient();
BlobRequestOptions options = new BlobRequestOptions();
options.UseFlatBlobListing = true;
CloudBlobContainer cbcFiles = new CloudBlobContainer("files", cbcClient);
CloudBlob cbKit = cbcFiles.GetBlobReference("Kit.exe");
ControllerContext.HttpContext.Response.Clear();
ControllerContext.HttpContext.Response.ContentType = "application/octet-stream";
ControllerContext.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=Kit.exe");
MemoryStream msFile = new MemoryStream();
cbKit.DownloadToStream(msFile);
msFile.Position = 0;
ControllerContext.HttpContext.Response.OutputStream.Write(msFile.ToArray(), 0, msFile.ToArray().Length);
ControllerContext.HttpContext.Response.Flush();
bReturn = bSuccess;
return bReturn;
}
這是由下面的函數調用:
[HttpPost]
public JsonResult Download()
{
try
{
bool bDlKit = DownloadKit();
}
catch (Exception ex)
{
//ToDo
}
return Json(null);
}
現在CSHTML文件具有以下JavaScript代碼:
$("#btnGetKit").click(function() {
$("#btnGetKit").hide();
$.ajax({
url: "AzureTest/Download",
type: "POST",
success: function() {
$("#btnGetKit").show();
}
})
}
這裏的問題是:當我在頁面加載時立即調用DownloadKit(),然後一切正常,我會提示下載文件。當我使用ajax機制時,即使代碼工作正常,也沒有提示下載文件。就好像OutputStream沒有被寫入一樣。
我會很感激有人給出一些指針。我是MVC的新手,所以仍然找到了解決方法。
謝謝。這很有用。但是,我需要下載一個在運行時生成的文件,所以沒有href。這個文件對於不同的用戶會有所不同。我仍在研究如何做到這一點。一旦找到解決方案,將在這裏發佈。 – Manas 2013-02-12 17:58:38
我得出的結論是,這是不可能的。解決方法是將動態生成的文件放入虛擬目錄位置。然後使用該位置作爲href。 – Manas 2013-03-09 01:05:04