我想使用Angular 6和Web API下载PDF。 这是代码实现,
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" });
}
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
答案 0 :(得分:4)
MSSQL
答案 1 :(得分:4)
我假设您正在使用.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?}");
答案 2 :(得分:1)
在某些浏览器中,我们需要动态创建Anchor标记并使其可点击才能下载文件。这是代码。
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
希望,这会有所帮助。谢谢。
答案 3 :(得分:0)
dataService.ts
downloadNoteReceipt(notes_purchased_id: number):Observable<Blob>{
return this.httpClient.get(this.baseUrl + `receipt/notespurchasedreceipt/` + notes_purchased_id, { responseType: "blob" } );
}
component.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>