I have a project where I am using NPOI to generate Excel document from my Angular application. I have the calls being made from my angular service to my webapi controller as follows:
function exportReportToExcel(report) {
return $http.post('reportlibrary/exportReport/', report, {
}).then(function (response) {
return response.data;
});
};
Within the controller I make the following call
[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);
}
}
This is a migration from an MVC app and previously I was able to return the object using System.IO.File to return the object as well as close the stream.
I've never done this with Angular but from what I have read it appears I can drop the memorystream object into a byteArray and pass that back to the client.
If this is the correct approach how to I unravel this object once it comes back to the angular service and controller.
The goal here is to allow the user to download a previously saved report as an Excel file.
Am I on the right track? Is there a more efficient way to download a memory stream object? How can I pass this context to the browser?
thanks in advance
I had a similar problem. I solved that changing the endpoint to support GET and calling this method from a new tab.
So from your angular app you have to create a new tab pointing to the path that calls the method that generate your document. You can open a tab with the next code:
I think that in the next link you can have all the information that you need:
Download file from an ASP.NET Web API method using AngularJS
I hope that it helps.