Je souhaite télécharger PDF à l'aide d'Angular 6 et de l'API Web. Voici l'implémentation du code,
mycomponent.ts
download(myObj: any) {
this.testService.downloadDoc(myObj.id).subscribe(result => {
var url = window.URL.createObjectURL(result);
window.open(url);
console.log("download result ", result);
});
}
myService.ts
downloadDoc(Id: string): Observable<any> {
let url = this.apiUrl + "api/myApi/download/" + Id;
return this.http.get(url, { responseType: "blob" });
}
Service API Web
[HttpGet("download/{DocId}")]
public async Task<HttpResponseMessage> GetDocument(string docId)
{
var docDetails = await _hoaDocs.GetDocumentDetails(docId).ConfigureAwait(false);
var dataBytes = docDetails.Stream;
var dataStream = new MemoryStream(dataBytes);
var response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(dataStream)
};
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = docDetails.File_Name
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
Quand j'exécute le code ci-dessus, cela ne télécharge pas le PDF, voici l'objet de résultat qui est enregistré dans la console
download result
Blob(379) {size: 379, type: "application/json"}
size:379
type:"application/json"
__proto__:Blob
Je suppose que vous utilisez .Net Core.
Vous renvoyez le type est HttpResponseMessage. Pour .Net Core, il devrait être IActionResult.
Donc, dans votre cas, vous reviendrez
return File(<filepath-or-stream>, <content-type>)
Ou
Vous devez apporter une petite modification dans votre fichier Startup.cs:
services.AddMvc().AddWebApiConventions();
Ensuite, je ne suis pas sûr à 100% ici, mais vous devez également modifier le routage:
routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
import { Injectable } from "@angular/core";
declare var $;
@Injectable()
export class DownloadFileService {
save(file, fileName) {
if (window.navigator.msSaveOrOpenBlob) {
// IE specific download.
navigator.msSaveBlob(file, fileName);
} else {
const downloadLink = document.createElement("a");
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.setAttribute("href", window.URL.createObjectURL(file));
downloadLink.setAttribute("download", fileName);
downloadLink.click();
document.body.removeChild(downloadLink);
}
}
}
Dans certains navigateurs, nous devons créer dynamiquement une balise Anchor et la rendre cliquable afin de télécharger des fichiers. Voici le code.
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
J'espère que cela t'aides. Merci.
dataService.ts
downloadNoteReceipt(notes_purchased_id: number):Observable<Blob>{
return this.httpClient.get(this.baseUrl + `receipt/notespurchasedreceipt/` + notes_purchased_id, { responseType: "blob" } );
}
composant.ts
download(booking_id: number) {
this.orderDetailsService.downloadNoteReceipt(booking_id).subscribe(res => {
console.log(res);
var newBlob = new Blob([res], { type: "application/pdf" });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob);
var link = document.createElement('a');
link.href = data;
link.download = "receipt.pdf";
// this is necessary as link.click() does not work on the latest firefox
link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}, error => {
console.log(error);
})
}
composant.html
<i class="fa fa-download" style="font-size:20px;color:purple" aria-hidden="true" (click)="download(row.booking_id)"></i>