ASP.net MVC 3不会下载生成的文件

时间:2012-11-15 08:39:03

标签: asp.net-mvc asp.net-mvc-3 actionresult fileresult

这是我的控制器的代码片段......一切都从我的索引开始。

 public ActionResult Index(...){
       //some code here
       return GenerateReport(...);
    }

到目前为止... exporter.GenerateReport()返回生成的excel文件的正确路径......

public ActionResult GenerateReport(...){
      string pathOfGeneratedFile = exporter.GenerateReport(...);
      return DownloadFile(pathOfGeneratedFile, "application/vnd.ms-excel");
}


public FileResult DownloadFile(string filePath, string contentType = "application/octet-stream"){
         return File(filePath, contentType, Path.GetFileName(filePath)); 
}

实际上没有任何错误/异常发生....但我希望我可以在生成文件后下载文件...我手动打开使用OpenXMl生成的文件,它确实打开了所有的信息存储在那里......

这是我的视图...我使用我的按钮的值进行了一些解析以反映GenerateReport用户操作....这将提交到Index操作,在该操作中,如果单击生成按钮,则确定用户操作。 ..

<input class="btn btn-primary pull-right" type="submit" value="Generate Report" name="userAction"/>

编辑:我也在我的观点中使用过这个......

@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "recordList", InsertionMode = InsertionMode.Replace }))

BTW,一旦完成所有操作......我可以在我的视图中看到垃圾值。我只想要下载文件。谢谢。

1 个答案:

答案 0 :(得分:2)

您无法下载文件的原因是您正在使用AJAX异步请求。 AJAX响应不能包含文件下载。您可以在控制器中尝试这样的事情:

public ActionResult Index(...) {
    var fileName = GenerateReport();

    // store the file name somewhere on the server - do NOT pass it through the URL.
    this.TempData["DownloadFileName"] = fileName;
    this.TempData["DownloadContentType"] = "application/vnd.ms-excel";
    this.TempData.Keep("DownloadFileName");
    this.TempData.Keep("DownloadContentType");

    return new JavaScriptResult() { Script = "document.location = \"" + this.Url.Action("Download") + "\";" };
}

public ActionResult Download() {
    return File((string)this.TempData["DownloadFileName"], (string)this.TempData["DownloadContentType"], Path.GetFileName(filePath)); 
}

因此,您的AJAX请求将导致重定向(无法使用RedirectToAction,因为这将导致浏览器在AJAX请求中重定向)。然后,此重定向将指示浏览器以经典请求下载文件。