gpt4 book ai didi

angular - 下载 PDF 文件、Angular 6 和 Web API

转载 作者:太空狗 更新时间:2023-10-29 17:05:14 25 4
gpt4 key购买 nike

我想使用 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?}");

关于angular - 下载 PDF 文件、Angular 6 和 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51624534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com