【问题标题】:How to download memory stream object via angularJS and webaAPI2如何通过 angularJS 和 webaAPI2 下载内存流对象
【发布时间】:2015-02-09 23:30:41
【问题描述】:

我有一个项目,我使用NPOI 从我的 Angular 应用程序生成 Excel 文档。我有从我的角度服务到我的 webapi 控制器的调用,如下所示:

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);
   }
}

这是从 MVC 应用程序的迁移,之前我能够使用 System.IO.File 返回对象以返回对象以及关闭流。

我从来没有用 Angular 做过这个,但从我读过的内容来看,我可以将 memorystream 对象放入一个 byteArray 并将其传递回客户端。

如果这是正确的方法,一旦它返回到角度服务和控制器,我如何解开这个对象。

这里的目标是允许用户将以前保存的报告下载为 Excel 文件。

我在正确的轨道上吗?有没有更有效的方法来下载内存流对象?如何将此上下文传递给浏览器?

提前致谢

【问题讨论】:

    标签: c# angularjs asp.net-web-api2 npoi


    【解决方案1】:

    我遇到了类似的问题。我解决了更改端点以支持 GET 并从新选项卡调用此方法的问题。

    因此,您必须从您的 Angular 应用程序中创建一个新选项卡,指向调用生成文档的方法的路径。您可以使用以下代码打开一个选项卡:

    $window.open(path)
    

    我认为在下一个链接中您可以获得所需的所有信息:

    Download file from an ASP.NET Web API method using AngularJS

    希望对你有帮助。

    【讨论】:

    • 不幸的是,这在这种情况下不起作用。我处理的不是文件而是内存/文件流,没有可调用的路径位置。
    • 路径是调用生成文档的端点的 url。 @rlcrews
    • 嗨,你解决了这个问题吗? @JVR
    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    相关资源
    最近更新 更多