我正在尝试发送一个 9MB 的 .xls
文件作为来自 web api Controller 方法的响应。用户将单击页面上的按钮,这将通过浏览器触发下载。
这是我到目前为止所得到的,但它不起作用,但它也不会抛出任何异常。
[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);
}
}
这是从界面中的按钮点击调用的 coffeescript/javascript jquery ajax。
$.ajax(
url: route
dataType: 'json'
type: 'GET'
success: successCallback
error: errorCallback
)
现在想想可能是dataType不对,不应该是json...
最佳答案
也可以用作 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);
}
关于c# - 通过 WebApi 调用从页面下载 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14831860/