C# 如何通过angularJS和webaAPI2下载内存流对象
我有一个项目,我正在使用它从我的Angular应用程序生成Excel文档。我的angular服务调用我的webapi控制器,如下所示:C# 如何通过angularJS和webaAPI2下载内存流对象,c#,angularjs,asp.net-web-api2,npoi,C#,Angularjs,Asp.net Web Api2,Npoi,我有一个项目,我正在使用它从我的Angular应用程序生成Excel文档。我的angular服务调用我的webapi控制器,如下所示: function exportReportToExcel(report) { return $http.post('reportlibrary/exportReport/', report, { }).then(function (response) { return respons
function exportReportToExcel(report) {
return $http.post('reportlibrary/exportReport/', report, {
}).then(function (response) {
return response.data;
});
};
在控制器内,我进行以下调用
[HttpPost]
public HttpResponseMessage ExportReport([FromBody]DTOs.Report report)
{
try
{
IReportPersistenceManager manager = ContainerConfigurator.Instance.Resolve<IReportPersistenceManager>();
MemoryStream ms = new MemoryStream();
//we have to pass to the NOPI assemble file type as well as file name
//since we only deal with excel for now we will set it but this could be configured later.
long id = report.ReportId;
string mimeType = "application/vnd.ms-excel";
string filename = "unknown";
manager.ExportDataToExcel(id, (name, mime) =>
{
mimeType = mime;
filename = name;
return ms;
});
ms.Position = 0;
var response = new HttpResponseMessage();
response.Content = new ByteArrayContent(ms.ToArray());
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
return (response);
}
catch (Exception)
{
//error
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
}
[HttpPost]
公共HttpResponseMessageExportReport([FromBody]DTOs.Report)
{
尝试
{
IReportPersistenceManager=ContainerConfiguration.Instance.Resolve();
MemoryStream ms=新的MemoryStream();
//我们必须传递到NOPI汇编文件类型以及文件名
//由于我们现在只处理excel,我们将设置它,但这可以在以后配置。
long id=report.ReportId;
字符串mimeType=“application/vnd.ms excel”;
字符串filename=“未知”;
manager.ExportDataToExcel(id,(名称,mime)=>
{
mimeType=mime;
filename=名称;
返回ms;
});
ms.Position=0;
var response=新的HttpResponseMessage();
response.Content=newbytearray内容(ms.ToArray());
response.Content.Headers.ContentType=新的MediaTypeHeaderValue(“application/vnd.ms excel”);
返回(响应);
}
捕获(例外)
{
//错误
返回新的HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
}
这是一个MVC应用程序的迁移,以前我可以使用System.IO.File返回对象并关闭流
我从未对Angular执行过此操作,但从我所读到的内容来看,似乎我可以将memorystream对象放入byteArray并将其传递回客户端
如果这是正确的方法,当这个对象返回到角度服务和控制器时,我如何分解它
这里的目标是允许用户下载以前保存为Excel文件的报告
我走对了吗?有没有更有效的方法下载内存流对象?如何将此上下文传递到浏览器
提前谢谢我也遇到了类似的问题。我解决了将端点更改为支持GET并从新选项卡调用此方法的问题 因此,从angular应用程序中,您必须创建一个新选项卡,指向调用生成文档的方法的路径。您可以打开带有下一个代码的选项卡:
$window.open(path)
我认为在下一个链接中,您可以获得所需的所有信息:
我希望它能有所帮助。不幸的是,在这种情况下,这不起作用。我不是在处理文件,而是处理内存/文件流,没有可调用的路径位置。路径是调用生成文档的端点的url@你解决这个问题了吗@JVR