Reputation: 21
I want to download the PDF and doc file on URL click event using the Angular6 and Web API.
Component.ts
download(ID: number) {
this._Services.download_test(ID).subscribe(res => {
const data = new Blob([res], { type: 'text/plain;charset=utf-8' });
saveAs(data, 'text.docx');
console.log(data);
});
}
Service.ts
public download_test(Id: number): Observable<Blob> {
const headers = new HttpHeaders().set('content-type', 'multipart/form-data');
return this.http.get(_baseUrl + 'GetFileDetail' + '?id=' + Id,
{ headers, responseType: 'blob' }).pipe(
map((res: Response) => {
console.log(res.headers);
console.log(res.blob());
return new Blob([res.blob()], { type: 'application/octet-stream' });
}
));
}
API
[HttpGet]
public HttpResponseMessage GetFileDetail(int id)
{
//Create HTTP Response.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
string fileName;
//Fetch the File data from Database.
Dictionary<string, object> rec;
DbConnection conn = CommonFunction.GetDBConnection();
conn.Open();
string qrystr = "SELECT FileName,FileType,FileContent "
+ " FROM tFileData "
+ " where ID = " + id;
rec = CommonFunction.GetSingleRecord(qrystr, conn);
if (rec.Count != 0)
{
Byte[] data = (Byte[])rec["FileContent"];
string Type = rec["FileType"].ToString();
fileName = rec["FileName"].ToString();
MemoryStream ms = new MemoryStream(data);
//Set the Response Content.
response.Content = new StreamContent(ms);
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentLength = data.LongLength;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
return response;
}
This code doesn't work for me. It throws the error:
ERROR TypeError: res.blob is not a function
Upvotes: 0
Views: 5517
Reputation: 21
I modified my service.ts file as below:
public download_test(Id: number): Observable<Blob> {
const headers = new HttpHeaders().set('content-type', 'multipart/form-data');
return this.http.get(_baseUrl + 'GetFileDetail' + '?id=' + Id,
{ headers, responseType: 'blob' });
}
and components.ts file:
download(ID: string) {
this._jobServices.download_test(ID).subscribe(res => {
const data = new Blob([res], { type: 'application/pdf' });
saveAs(data);
console.log(data);
});
}
It's working. Thank you!
Upvotes: 1