1

我有这个功能,它执行实际的文件下载(在一个名为 AzureTest 的控制器中);它是一个 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 的新手,所以仍然在寻找我的方式。

4

1 回答 1

0

I don't think it's possible. Based on this thread: Download a file by jQuery.Ajax, JavaScript cannot save files directly to a user's computer. However do take a look at jQuery File Download Plugin (http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx) and see if that works for you.

于 2013-02-09T12:34:13.323 回答