c# - 调用WEB API下载excel文件
问题描述
下面是生成 Excel 的 C# WEB API 代码:
public class FileExportController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
var callerContext = CallerContext.DefaultCallerContext;
ReportingInput userInput = new ReportingInput();
userInput.ClientOneCode = "AVON";
string handle = Guid.NewGuid().ToString();
var @event = new GetJobReprotDataBlEvent(callerContext, userInput);
WebApiApplication.ApplicationInitializerObj.EventBus.Publish(@event);
XLWorkbook wb = new FileExportEngine().ExportExcel(@event.ReportData); //this is returning XLWorkbook
string fileName = "JobReport_" + DateTime.Now.ToString("yyyy -MM-dd HH':'mm':'ss") + ".xlsx";
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
当我从浏览器调用这个 API 时,我能够生成 excel 文件。 http://localhost/ETLScheduler/api/FileExport - 在浏览器中直接点击时有效
现在我想在 Angular 5 应用程序中使用这个 API。我有一个按钮。点击按钮时,我调用组件方法 downloadFile() 来下载文件。下面是代码:
downloadReport() {
this._service.downloadJobReport('AVON');
}
其中 downloadJobReport() 在我的服务文件中,如下所示:
downloadJobReport(clientCode: string) {
return this._http.get(APIs.downloadJobReport);
}
当我运行应用程序并单击下载按钮时,我什么也没得到,我的意思是文件没有下载。谁能知道,我应该如何更新我的角度代码来使用 API。
提前致谢。
解决方案
问题是,Angular 期望 JSON 作为结果。您需要配置您的 GET 请求,以便它期望不同的东西。
public downloadJobReport(clientCode: string)): Observable<Blob> {
return this._http.get(APIs.downloadJobReport, { responseType: 'blob' });
}
只是一个小问题,您将参数 clientCode 传递给 downloadJobReport,但从不使用它。也许明智的把它排除在外?
推荐阅读
- sql - 更新 SQL 表将行标识为行数
- node.js - 如何在 Node.js 中解析 YAML 文件
- xcode - RN 错误:未找到 BTPayPalDriver_Internal.h' 文件
- websocket - 如何在 IIS 服务器上部署烧瓶套接字 io 应用程序?
- javascript - React 测试错误:未捕获 [TypeError:无法读取未定义的属性“映射”]
- java - 选项菜单中的居中对齐复选框
- wordpress - 定制woocommerce分析产品报告
- javascript - TypeError:cursor.toArray 不是 Node js 的函数
- django - 解析 GraphQL 查询以查找能够预取相关的字段?
- maven - 我可以让 maven-war-plugin *only* 复制 classes.jar 而不是 .war 到本地 repo 吗?