João Silva João Silva - 4 months ago 85
ASP.NET (C#) Question

Angular 2 save Excel File

I'm trying to save a Excel File from my server to Client PC but it get all messed up.

When I request my file to the server the body of the request comes like this:


��ࡱ�>�� &����


I guess it's normal since excel is in binary format. I'm using file-saver plugin to save my files, at the moment I have the CSV and ASCII files working well.
This is my function to download:

downloadFile(filePath: string, name: string): void{
this.dataImportService.downloadFile(filePath)
.then(data => {
this.headers = data.headers;
let content = this.headers.get('content-type');
var blob = new Blob([data._body], { type: content });
importedSaveAs(blob, name);
});
}


Anything that I'm doing wrong or that I can improve?
Thank you in advance for the help.

EDIT: This is my server code:

[HttpGet]
public void downloadFile(string path)
{
try
{
string extension = Path.GetExtension(path);
string fileName = Path.GetFileName(path);

HttpResponse response = System.Web.HttpContext.Current.Response;

response.AppendHeader("Content-Disposition", "attachment; filename="+fileName);
response.AddHeader("Content-Type", Utils.MimeTypesConverter.GetMimeType(extension));

response.TransmitFile(path);
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.Message);
return;
}

}


and my dataImportService.ts

downloadFile(filePath: string): any{
return this.http.get(SERVICE_URL + 'DataImport/downloadFile?path=' + filePath)
.toPromise()
.then(response =>{
return response;
})
.catch(this.handleError);
}


My http response from server:

enter image description here

Answer Source

You have to map the Response which includes HTTP Headers to the Blob on it's own. So change code to an Observable wtih a map to transform response.

downloadFile(filePath: string): Observable<any> { 
  return this.http.get(
  `${SERVICE_URL}DataImport/downloadFile?path=${filePath}`, 
  {responseType: ResponseContentType.Blob }
) 
.map(res:Response => res.blob()); 
}