通过WebApi调用从页面下载excel文件

我试图发送一个9MB的.xls文件作为从Web API控制器方法的响应。 用户将点击页面上的button,这将通过浏览器触发下载。

这是我到目前为止,但它不起作用,但它也不会抛出任何例外。

 [AcceptVerbs("GET")] public HttpResponseMessage ExportXls() { try { byte[] excelData = m_toolsService.ExportToExcelFile(); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new MemoryStream(excelData); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Data.xls" }; return result; } catch (Exception ex) { m_logger.ErrorException("Exception exporting as excel file: ", ex); return Request.CreateResponse(HttpStatusCode.InternalServerError); } } 

这里是从界面中点击button的coffeescript / javascript jquery ajax调用。

 $.ajax( url: route dataType: 'json' type: 'GET' success: successCallback error: errorCallback ) 

现在,我想这可能是dataType是错误的,不应该是JSON …

我不得不做一些小的改变才能使这个工作

首先:将方法更改为post

 [AcceptVerbs("POST")] 

第二:从使用jQuery ajax lib改变使用隐藏的forms,这里是我的服务function做隐藏的forms和提交。

 exportExcel: (successCallback) => if $('#hidden-excel-form').length < 1 $('<form>').attr( method: 'POST', id: 'hidden-excel-form', action: 'api/tools/exportXls' ).appendTo('body'); $('#hidden-excel-form').bind("submit", successCallback) $('#hidden-excel-form').submit() 

希望有一个更好的方法来做到这一点,但目前正在工作,并很好地下载Excel文件。

也可以作为一个HTTP GET方法,但不要使用$ ajax,而是使用window.open(url);

C#代码:

  [HttpGet] [Route("report/{scheduleId:int}")] public HttpResponseMessage DownloadReport(int scheduleId) { var reportStream = GenerateExcelReport(scheduleId); var result = Request.CreateResponse(HttpStatusCode.OK); result.Content = new StreamContent(reportStream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Schedule Report.xlsx" }; return result; } 

JS代码:

 downloadScheduleReport: function (scheduleId) { var url = baseUrl + 'api/Tracker/report/' + scheduleId; window.open(url); } 

这将返回一个文件,当你点击一个特定的button

  public FileResult ExportXls(){ //the byte stream is the file you want to return return File(bytes, "application/msexcel") }