Mad*_*dhu 11 asp.net-core-webapi angular angular6
我想使用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);
});
}
Run Code Online (Sandbox Code Playgroud)
myService.ts
downloadDoc(Id: string): Observable<any> {
let url = this.apiUrl + "api/myApi/download/" + Id;
return this.http.get(url, { responseType: "blob" });
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
当我执行上面的代码时,它没有下载PDF,这是在控制台中记录的结果对象
download result
Blob(379) {size: 379, type: "application/json"}
size:379
type:"application/json"
__proto__:Blob
Run Code Online (Sandbox Code Playgroud)
小智 5
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我假设您正在使用.Net Core。
您返回的类型是HttpResponseMessage。对于.Net Core及更高版本,应为IActionResult。
因此,就您而言,您将返回
return File(<filepath-or-stream>, <content-type>)
Run Code Online (Sandbox Code Playgroud)
要么
您必须在Startup.cs文件中做一个小的更改:
services.AddMvc().AddWebApiConventions();
Run Code Online (Sandbox Code Playgroud)
然后,我不确定这里是否100%,但是您也必须更改路由:
routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21085 次 |
| 最近记录: |