【发布时间】:2016-01-07 21:55:51
【问题描述】:
我编写了使用 Angular $http 下载文件的代码。文件名没有在 URL 中指定。 URL 包含文件的唯一标识符,该标识符是从应用程序外部获取的。
当$http.get(myUrl) 被调用时,一切正常;该文件被检索,我可以在我的回调处理程序中访问它,但我看不到如何获取文件的名称。使用 Fiddler 捕获原始响应,我看到了:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 54
Content-Type: application/octet-stream
Server: Microsoft-IIS/8.5
Access-Control-Allow-Origin: http://www.example.com/getFile/12345
Access-Control-Allow-Credentials: true
Content-Disposition: attachment; filename=testfile.txt
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 09 Oct 2015 20:25:49 GMT
Lorem ipsum dolar sit amet! The contents of my file!
从上面可以清楚地看出,服务器正在“Content-Disposition”中发回文件的名称,但我还没有找到在我的 Angular 回调中访问它。如何从标题中获取文件名?
根据以下答案进行编辑:
我之前应该提到我已经尝试过response.headers()。它返回Object {content-type: "application/octet-stream", cache-control: "private"},所以由于某种原因我仍然没有得到Content-Disposition。 response.headers('Content-Disposition') 返回null。
【问题讨论】:
-
如果
response.headers('Content-Disposition') returns null显然有问题。 @andrew 的答案很完美 -
您找到解决方案了吗?我有完全相同的问题:Fiddler 清楚地显示了正确的内容处置标头,但以下解决方案均无效: response.headers('Content-Disposition') 返回 null
-
我能够让它在我正在执行的特定任务的上下文中工作,但我没有一个好的通用答案。
-
如果
response.headers('Content-Disposition') returns null并且您在 API 中使用 CORS,则需要确保在响应中添加此标头:access-control-expose-headers:content-dispositionstackoverflow.com/a/44504121/2069306 -
将
Response.Headers.Add(HeaderNames.AccessControlExposeHeaders, "content-disposition");添加到请求函数中,它将授予对该特定调用的脚本的读取权限
标签: angularjs http-headers blob