2017-07-29 67 views
1

我有一個REST API,如果我直接在瀏覽器中查詢,它會返回一個JSON或CSV文件進行下載。我想用Angular HttpModule做同樣的事情。Angular 4 HttpModule如何從獲取請求中返回文件

我的GET請求是簡單的(它有一個查詢字符串參數去指示哪些文件格式返回):

public Submit(request: Request) { 
    ... 
    return this.http.get(url).subscribe(response => { 
    //What here 
    }); 
} 

響應內容類型爲application/octet-stream。我已經嘗試將響應作爲blob處理,但不起作用。我如何才能通過從服務器到瀏覽器的響應並讓它下載文件?這種方法是一個正在由是響應一個按鈕組件調用服務的一部分,單擊

onClick() { 
    this._requestService.Submit(request); //This gets the Subscription response from the service, but I want it to let the broswer download the file 
} 

回答

0

我得到大部分解決方案從AngularJS $http-post - convert binary to excel file and downloadAngularJS: Display blob (.pdf) in an angular app

let ieEDGE = navigator.userAgent.match(/Edge/g); 
let ie = navigator.userAgent.match(/.NET/g); // IE 11+ 
let oldIE = navigator.userAgent.match(/MSIE/g); 

let blob = new Blob([response.text()], { type: "application/octet-stream"}); 
let fileName: string = "myfile." + this.request.output; 

if (ie || oldIE || ieEDGE) { 
    window.navigator.msSaveBlob(blob, fileName); 
} 
else { 
    let link = document.createElement('a'); 
    link.href = window.URL.createObjectURL(blob); 
    link.download = fileName; 
    link.click(); 

    setTimeout(function() { 
    window.URL.revokeObjectURL(url); 
    }, 0); 
} 

對於非IE瀏覽器(以下簡稱「其他人」的聲明),我也能夠成功地使用

let reader = new FileReader(); 
reader.onloadend = function() { 
    window.location.href = reader.result; 
}; 

reader.readAsDataURL(blob); 

對於第二種方法,這一點很重要的是,BLOB類型是application/octet-stream,否則的東西如application/jsontext/csv,它會在新窗口/選項卡中打開文件。缺點是你不能提供文件名或擴展名,所以你得到一個名爲「下載」的原始文件。

0

你可以嘗試這樣的事:

this.http.get(url).subscribe(response => { 
    const blob = new Blob([response], { type: 'text/csv' }); 
    const url= window.URL.createObjectURL(blob); 
    window.open(url); 
}); 
+0

試過,我得到一個錯誤:'資源'blob:6BB5A3D5-0D0D-4537-B4F3-888D7A70DE57'不允許加載.' – hakenmt

1

您必須添加

{ responseType: ResponseContentType.Blob } 

然後映射響應斑點。

return this.http.get(url, { responseType: ResponseContentType.Blob }) 
    .map(r => r.blob()) 
    .subscribe(response => { 

    }); 

接下來,您可以使用fileSaver.js下載此文件。