【问题标题】:Downloading an excel file from ASP.net Core API从 ASP.net Core API 下载 excel 文件
【发布时间】:2019-12-18 13:02:21
【问题描述】:

所以我们的自定义 API 返回:

var result = File(
                new MemoryStream(report, 0, report.Length),
                "application/octet-stream",
                $"missionreport_{DateTime.Now}.xlsx");

return result;

当浏览到正确的 API 调用时,它会立即下载具有相应名称和样式的正确 Excel 文件。

现在我们想用一个 Angular 前端来做到这一点。我们创建了以下内容:

rapport.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { tap, catchError, map } from 'rxjs/operators';

@Injectable()
export class RapportService {
    private url = "http://localhost:50000/api/report";

    constructor(private http: HttpClient){}

    getMissionReport() {
        return this.http.get(`${this.url}/mission`, {responseType: 'blob'})
                        .pipe(
                                tap(data => console.log('Get mission report: ' + data)),
                                catchError(this.handleError)
                        )
    }

    private handleError(err: HttpErrorResponse) {
        let errorMessage = '';
        if (err.error instanceof ErrorEvent) {
            errorMessage = `An error occurred: ${err.error.message}`;
        } else {
            errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
        }
        console.error(errorMessage);
        return throwError(errorMessage);
    }
}

rapport.component.ts:

getMissionRapport() {
    this.rapportService.getMissionReport().subscribe(response => {
      const blob = new Blob([response], {type: 'application/octet-stream'});
      const url = window.URL.createObjectURL(blob);
      window.open(url);
    })
  }

我们将该功能链接到一个按钮。单击此按钮时,我们收到一个仅显示字节值的“文件”。

【问题讨论】:

  • 如何将内容类型从“application/octet-stream”更改为“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”?
  • 这确实是正确答案。

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


【解决方案1】:

代码的问题是{type: 'application/octet-stream'}。您正在指定 application/octet-stream 要以哪种格式保存文件。因此你得到一个流。

您必须指定正确的类型才能将文件下载为 excel、pdf 或任何格式

application/pdf // for pdf 
application/vnd.openxmlformats-officedocument.wordprocessingml.document // for Word doc
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet // for excel

【讨论】:

  • 我的英雄!如何指定文件名?
猜你喜欢
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 2020-08-31
相关资源
最近更新 更多