我有一个Web服务,该服务返回pdf文件(字节[])和响应标题中的文件名。
我可以在Chrome上看到“响应标题”的值,并且每个人都在那儿(包括文件名)。但是我无法在Angular上获得此值,因为标头值只是“ Content-Type:application / pdf”。
我的Angular代码:
getPdf(url: string){
http.get(url, {responseType: 'arraybuffer', observe:'response'})
.subscribe(data => {
console.log(data.headers.get('filename')); // print: null
console.log(data.headers.keys()); // print: ["Content-Type"],
downloadFile(data.body);
});
}
浏览器上的响应标题:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin, X-Request-Width, Content-Type, Accept, authCode
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Disposition:attachment; filename=file.pdf
Content-Type:application/pdf
Date:Mon, 26 Nov 2018 14:23:37 GMT
filename:file.pdf
Server:JBoss-EAP/7
Transfer-Encoding:chunked
X-Powered-By:Undertow/1
有什么问题吗?如何正确执行此操作?
答案 0 :(得分:0)
我使用Web服务上的“ Access-Control-Expose-Headers”解决了我的问题。
我的Java网络服务:
protected Response buildFile(Status status, byte[] file, String nomeArquivo) {
return Response.status(status)
.entity(file)
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Expose-Headers", "Content-Disposition, filename")
.header("Content-Type", "application/pdf")
.header("Content-Disposition", "attachment; filename="+ nomeArquivo)
.header("filename", nomeArquivo)
.build();
}
更多信息: How to get the name of a file downloaded with Angular5