【发布时间】:2017-01-20 19:30:51
【问题描述】:
我正在尝试下载使用 ClosedXML 创建的文件。我已经验证该文件没有损坏,但由于某种原因,它只适用于 Angular1,而不是 Angular2。返回文件的web api代码为:
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(ms.GetBuffer());
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
return response;
在 Angular2 中,在我的网络服务中:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('responseType', 'arrayBuffer');
this.observableDataGet = this._http.post(`${AppSettings.REPORTS_API_URL}/Report/MonthlySpreadsheet`, {headers: this.getHeaders()})
.map(response => {
if (response.status == 400) {
return "FAILURE";
} else if (response.status == 200) {
var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
var blob = new Blob([response.arrayBuffer()], { type: contentType });
return blob;
}
})
在我的组件中:
.subscribe(blob => {
var downloadUrl= URL.createObjectURL(blob);
window.open(downloadUrl);
},
一个文件已下载,但当我尝试访问它时它已损坏,并且是使用 Angular1 下载时文件大小的两倍。
如果我用 Angular1 调用 SAME API,文件下载正常。
我的服务代码:
function generateMonthlySpreadsheet(header) {
var request = $http({
method: "post",
responseType: 'arraybuffer',
url: TEST_API_URL + 'Report/MonthlySpreadsheet',
timeout: 30000,
headers: header
});
return ( request.then(handleSuccess, handleError) );
}
handleSuccess 返回 response.data 的位置(对于 angular2 我无法获取)
以及调用服务的代码:
alertAppService.generateMonthlySpreadsheet(header).then(function (data){
var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
有趣的是,在 Angular2 中,如果我只是将我的 web 服务更改为 GET(我想要 POST,但只是为了尝试一下)然后摆脱服务代码并简单地进行此调用,文件就可以了:
window.open(`${AppSettings.REPORTS_API_URL}/Report/MonthlySpreadsheet`, "_blank");
那么,真的,这里有什么区别?为什么相同或非常相似的代码适用于 Angular1 而不是 Angular2?
-- 卡伦
【问题讨论】:
标签: angular