下载PDF文件,Angular 6和Web API



我想使用Angular 6和Web API下载PDF。以下是代码实现,

分枝杆菌成分.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" });
}

Web API服务

[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;
}

当我执行上面的代码时,它不是下载PDF,这是记录在控制台中的结果对象

download result  
Blob(379) {size: 379, type: "application/json"}
size:379
type:"application/json"
__proto__:Blob

我假设您使用的是.Net Core。

您的返回类型为HttpResponseMessage。对于.Net Core以后的版本,它应该是IActionResult。

因此,在您的情况下,您将返回

return File(<filepath-or-stream>, <content-type>)

你必须在Startup.cs文件中做一个小改动:

services.AddMvc().AddWebApiConventions();

然后,我在这里不是100%确定,但你也必须改变路线:

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);
}
}
}

在某些浏览器中,我们需要动态创建Anchor标记并使其可点击才能下载文件。这是代码。

const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();

希望,这有帮助。谢谢

dataService.ts

downloadNoteReceipt(notes_purchased_id: number):Observable<Blob>{    
return this.httpClient.get(this.baseUrl + `receipt/notespurchasedreceipt/` + notes_purchased_id, { responseType: "blob" } );
}

组件.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);
})
}

component.html

<i class="fa fa-download" style="font-size:20px;color:purple" aria-hidden="true" (click)="download(row.booking_id)"></i>

最新更新