2015-02-09 18 views
1

我有一個項目,我使用NPOI從我的Angular應用程序生成Excel文檔。我有電話從我的角度服務正在爲我的WebAPI控制器如下:如何通過angularJS和webaAPI2下載內存流對象

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文件。

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

在此先感謝

回答

2

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

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

$window.open(path) 

我認爲,在未來的鏈接,你可以有你需要的所有信息:

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

我希望它幫助。

+0

不幸的是,在這種情況下不起作用。我沒有使用文件,而是使用內存/文件流,沒有路徑位置調用。 – rlcrews 2015-02-10 14:17:38

+1

路徑是調用生成文檔的端點的url。 @rlcrews – jvrdelafuente 2015-02-10 14:31:19

+0

嗨你解決了這個問題嗎? @JVR – 2016-11-25 14:57:42