【问题标题】:Error downloading .xlsx file using http.get in angular with asp.net web api使用带有asp.net web api的角度的http.get下载.xlsx文件时出错
【发布时间】:2019-11-22 11:49:54
【问题描述】:

我正在尝试在 c# 中使用 Angular 7 和 web api 下载 .xlsx 文件 但我收到此错误:

我的服务.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 文件已正确导出

【问题讨论】:

    标签: c# angular typescript asp.net-web-api


    【解决方案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

    【讨论】:

      【解决方案2】:

      服务.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文件生成正确

      【讨论】:

        猜你喜欢
        • 2015-07-18
        • 2017-04-21
        • 2012-08-30
        • 2018-03-20
        • 2019-01-29
        • 2019-02-01
        • 2021-10-12
        • 1970-01-01
        • 2017-10-17
        相关资源
        最近更新 更多