我正在尝试使用C#中的Angular 7和Web API下载.xlsx文件 但我收到此错误:
我的service.ts
public exportExcelFile(matchedRows: string, reportInfoId: number): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({ 'responseType': 'ResponseContentType.Blob',
'Content-Type': 'application/vnd.ms-excel'})};
const url = `${environment.apiUrl}report/${reportInfoId}/exportExcelFile?matchedRows=${matchedRows}`;
return this.http.get(url, httpOptions);
}
“消耗”我的服务的方法:
exportExcelFile(matchedRows:string){
this.service.exportExcelFile(matchedRows, this.reportInfo.ide).subscribe((response)=>{
console.log(response)
})
this.exportingExcelFile=false;
this.ready=true;
}
从API检索我的响应的方法
[HttpGet]
public IHttpActionResult ExportExcelFile(int reportId, bool matchedRows)
{
var user = Request.GetAuthenticatedUser();
var query = new GetExcelFileQuery(reportId, user.UserName, matchedRows);
var result = _dispatcher.Dispatch<GetExcelFileQuery, GetExcelFileModel>(query);
using (var memoryStream = new MemoryStream()) //creating memoryStream
{
result.Workbook.Write(memoryStream);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(memoryStream.ToArray());
response.Content.Headers.ContentType = new MediaTypeHeaderValue
("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = result.FileName
};
return result == null ? NotFound() : (IHttpActionResult)new FileResult(response);
}
}
如果我直接使用浏览器上的URL访问,则excel文件已正确导出
答案 0 :(得分:1)
您的后端很好。客户端试图解析响应,因为它是一个json文件。
'responseType'
应该只是'blob'
,并且应该将其放置在HttpHeaders对象的外部。您可以根据情况忽略整个httpHeaders对象
const url = `${environment.apiUrl}report/${reportInfoId}/exportExcelFile?matchedRows=${matchedRows}`;
return this.http.get(url, {responseType: 'blob'});
有关responseType对象的一些其他信息: https://angular.io/api/common/http/HttpRequest#responseType
答案 1 :(得分:0)
Service.ts
public exportExcelFile(matchedRows: string, reportInfoId: number): Observable<any> {
const url = `${environment.apiUrl}report/${reportInfoId}/exportExcelFile?matchedRows=${matchedRows}`;
return this.http.get(url,{ observe: 'response', responseType: 'blob'} );
}
调用我的服务的方法
exportExcelFile(matchedRows:string){
this.service.exportExcelFile(matchedRows, this.reportInfo.ide).subscribe((response)=>{
const blob = new Blob([response.body],
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const file = new File([blob], 'reports.txt',
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(file);
})
使用
import { saveAs } from 'file-saver';
Excel文件正确生成