2017-06-05 106 views
0

我想允許用戶從下拉列表中選擇要下載的文件。一旦他們做出選擇,他們可以點擊下載按鈕。但是,該文件不能正確下載。通過AJAX POST的MVC下載文件

這裏是用於生成並返回文件,所述控制器:

[HttpPost] 
    public ActionResult DownloadReport(int? id, string templateChoice) 
    { 
     if (id == null) 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     try 
     { 
      byte[] file = GetReport(id, templateChoice); 
      return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx"); 
     } 
     catch (InvalidOperationException) 
     { 
      return View(); 
     } 
    } 

JavaScript函數,其在按壓生成報告按鈕稱爲是:

function downloadReport(InputID) { 
     $.ajax({ 
      type: 'POST', 
      url: '@Url.Action("DownloadReport", "UserProfiles")', 
      data: JSON.stringify({ "ID": InputID, "TemplateChoice": $("#resumeTemplates").val() }), 
      contentType: 'application/json; charset=utf-8' 
     }); 
    } 

打開檢查窗口中鉻和轉到網絡選項卡顯示收到的文檔數據,但它不像常規文件那樣下載。

+0

你沒有從服務器獲取JSON,它是二進制的。看到這個https://stackoverflow.com/a/18450007/4607796 –

回答

0

我似乎找到了一個工作解決方案,它不會不是重新加載頁面,不會重定向用戶,並且在按下下載按鈕時不會在URL中顯示任何多餘的文本。我取代我用下面的電流JavaScript函數:

function downloadReport(inputID) { 
     window.location.href = '/UserProfiles/DownloadReport/?id=' + inputID + '&template=' + $('#resumeTemplates').val(); 
    } 

我的控制器現在看起來像:

public ActionResult DownloadReport(int? id, string template) 
    { 
     if (id == null || template == null) 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     try 
     { 
      byte[] file = GetReport(id, template); 
      return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx"); 
     } 
     catch (InvalidOperationException) 
     { 
      return View(); 
     } 
    } 

我也加入到這一點我RouteConfig.cs文件:

routes.MapRoute(
      "DownloadReport", 
      "{controller}/{action}/{id}/{template}", 
      new { controller = "UserProfiles", action = "DownloadReport", id = UrlParameter.Optional, template = UrlParameter.Optional } 
     );