正在调用 WEB API 下载 excel 文件

Calling WEB API to download excel file

下面是 C# WEB API 代码生成 Excel :

public class FileExportController : ApiController
{

    [HttpGet]
    public HttpResponseMessage Get()
    {
        var callerContext = CallerContext.DefaultCallerContext;
        ReportingInput userInput = new ReportingInput();
        userInput.ClientOneCode = "AVON";
        string handle = Guid.NewGuid().ToString();
        var @event = new GetJobReprotDataBlEvent(callerContext, userInput);
        WebApiApplication.ApplicationInitializerObj.EventBus.Publish(@event);
        XLWorkbook wb = new FileExportEngine().ExportExcel(@event.ReportData); //this is returning XLWorkbook
        string fileName = "JobReport_" + DateTime.Now.ToString("yyyy -MM-dd HH':'mm':'ss") + ".xlsx";
        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream);

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(memoryStream.ToArray())
            };
            result.Content.Headers.ContentDisposition =
                new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue("application/octet-stream");

            return result;
        }

    }

当我从浏览器调用此 API 时,我能够生成 excel 文件。 http://localhost/ETLScheduler/api/FileExport -- 在浏览器中直接点击时有效

现在我想在 angular 中使用这个 API 5 application.I 有一个 button.On 单击按钮 我调用组件方法 downloadFile() 来下载文件. 下面是代码:

downloadReport() {     
    this._service.downloadJobReport('AVON');
}

downloadJobReport() 在我的服务文件中的位置如下:

downloadJobReport(clientCode: string) {
    return this._http.get(APIs.downloadJobReport);
}

当我在 运行 应用程序并单击下载按钮时,我什么也没得到,我的意思是文件没有下载。任何人都可以知道,我应该如何更新我的 angular 代码以使用 API.

提前致谢。

问题是,Angular 期望结果是 JSON。您需要配置您的 GET 请求,以便它期望不同的东西。

public downloadJobReport(clientCode: string)): Observable<Blob> {   
    return this._http.get(APIs.downloadJobReport, { responseType: 'blob' });
}

只是一个小问题,您将参数 clientCode 传递给 downloadJobReport,但从未使用它。也许把它排除在外是明智的?

正如您在评论中提到的,您正在使用以下 angular 代码下载文件:

 downloadFile(data: Blob) { 
    const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; 
    const blob = new Blob([data], { type: contentType });
    const url = window.URL.createObjectURL(blob);
    window.open(url);
}

因为我也试过这段代码,它在 chrome 浏览器中工作但在 IE 和 edge 中不工作。

您可以像下面这样更新您的方法:

var downloadFile=function (file_name, content) {
var csvData = new Blob([content], { type: 'text/csv' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE
    window.navigator.msSaveOrOpenBlob(csvData, file_name);
} else { // for Non-IE (chrome, firefox etc.)
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    var csvUrl = URL.createObjectURL(csvData);
    a.href =  csvUrl;
    a.download = file_name;
    a.click();
    URL.revokeObjectURL(a.href)
    a.remove();
}

};

您可以参考下面link了解更多信息:

Open links made by createObjectURL in IE11