suresh
suresh

Reputation: 43

Calling WEB API to download excel file

below is C# WEB API Code to generate 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;
        }

    }

When I call this API from browser, I am able to generate excel file. http://localhost/ETLScheduler/api/FileExport -- this is working when hit direct in browser

Now I want to use consume this API in angular 5 application.I have a button.On click button I call the component method downloadFile() to download the file. Below is the code :

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

where downloadJobReport() is in my service file as below :

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

When I am running the application and click on Download button, I am getting nothing, I mean file is not downloading. Can anyone have idea,how should I update my angular code to consume the API.

Thanks in advance.

Upvotes: 2

Views: 13244

Answers (2)

Suresh Negi
Suresh Negi

Reputation: 422

As you mentioned above in comments you are using below angular code to download file:

 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);
}

As I also have tried this code, it is working in chrome browser but not working in IE and edge.

You may update your method somthing like below:

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();
}

};

you can refer below link for more information:

Open links made by createObjectURL in IE11

Upvotes: 2

Eduard Keilholz
Eduard Keilholz

Reputation: 933

Problem is, that Angular expects JSON as a result. You need to configure your GET request so, that it expects something different.

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

Just a tiny question, you pass an argument clientCode to the downloadJobReport, but never use it. Maybe wise to leave that out?

Upvotes: 1

Related Questions