I'm using webapi project in c# and angular I implemented a function in the controller that exports an excel file, and another funtion in the angular service to import this excel.
The c# funtion works great , it creates a new excel, and saves it into some path.
The problem happens in the angular: Unexpected token P in JSON at position 0
Here is my code:
C# controller:
[HttpGet]
[Route("downloadProducts/{userID}")]
public HttpResponseMessage DownloadProducts(int userID)
{
var pathToExcel=WriteExcel.GetPathToProducts(userID);
var buffer = File.ReadAllBytes(pathToExcel);
var stream = new MemoryStream(buffer);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "products.xlsx"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
Angular service:
downloadFile (userID:number):Observable<Blob>{
return this.http.get<Blob>(`${this.url}/downloadProducts/${userID}`);
}
Componenet.TS
const EXCEL_TYPE = 'application/octet-stream';
this.productsService.downloadloadFile(this.user.userID).subscribe(data=>{
var file = new Blob([data], { type: EXCEL_TYPE });
this.href = window.URL.createObjectURL(file);
setTimeout(() => {
console.log(this.href);
}, 500);
window.open(this.href);
})
What should I fix?
Thanks a lot.
CodePudding user response:
Here in above function use MIME type text/csv instead of application/octet-stream it can download file using .xlsx extension.
Do not convert it to Blob try without it.
downloadFile (userID:number):Observable<any>{
return this.http.get<any>(`${this.url}/downloadProducts/${userID}`);
}