簡體   English   中英

如何通過angularJS和webaAPI2下載內存流對象

[英]How to download memory stream object via angularJS and webaAPI2

我有一個項目,正在使用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文件。

我在正確的軌道上嗎? 有沒有更有效的方法來下載內存流對象? 如何將該上下文傳遞給瀏覽器?

提前致謝

我有一個類似的問題。 我解決了更改端點以支持GET並從新選項卡調用此方法的問題。

因此,從您的角度應用程序中,您必須創建一個新選項卡,該選項卡指向調用生成文檔的方法的路徑。 您可以使用以下代碼打開一個標簽:

$window.open(path)

我認為在下一個鏈接中,您可以擁有所需的所有信息:

使用AngularJS從ASP.NET Web API方法下載文件

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM