I am trying to download a file that I created with ClosedXML. I have verified that the file is not corrupt but, for some reason, it works just with Angular1, not Angular2.
this is the solution I used to Dwobnload the complete file with style (colors..)
The WebApi:
[HttpGet]
[Route("api/RapproResult/DownloadExcelReport/{reportName}")]
public HttpResponseMessage DownloadExcelReport( string reportName)
{
try
{
string filePath = HttpContext.Current.Server.MapPath("~/Report/Report_TEST.XLS");
if (!string.IsNullOrEmpty(filePath ))
{
using (MemoryStream ms = new MemoryStream())
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new ByteArrayContent(ms.GetBuffer());
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
}
}
return this.Request.CreateResponse(HttpStatusCode.NotFound, "File not found.");
}
catch (Exception ex)
{
return this.Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}
this is the angular service :
protected downloadExcelReportService( reportName: string) {
let completeUrl = this.downloadExcelReportUrl+reportName;
return Observable.create(observer => {
let xhr = new XMLHttpRequest();
xhr.open('GET', completeUrl, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.responseType='blob';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
debugger;
var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
var blob = new Blob([xhr.response], { type: contentType });
observer.next(blob);
observer.complete();
return observer;
} else {
observer.error(xhr.response);
}
}
}
debugger;
xhr.send();
});
}
And finally the Angular component method using FileSaver Api
import * as FileSaver from "file-saver";
downloadexcelReport(data)
{
this._servive.downloadExcelReport(data.RapproName)
.subscribe(
_data => FileSaver.saveAs(_data, data.RapproName+".xls" ) ),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.');
}
I hope that helps you.