如何在JavaScript中检索HttpResponseMessage文件名

如何在JavaScript中检索HttpResponseMessage文件名,javascript,angularjs,asp.net-web-api,Javascript,Angularjs,Asp.net Web Api,我有一个WebAPI方法,它将一个自定义对象MyType作为输入,并基于它生成一个PDF。PDF文件以HttpResponseMessage的形式返回。请注意,我在response.Content.Headers.ContentDisposition.filename上指定了文件名: ASP.NET WebAPI [Route("")] public HttpResponseMessage Get([FromUri]MyType input) { var pdfContent = Pdf

我有一个WebAPI方法,它将一个自定义对象
MyType
作为输入,并基于它生成一个PDF。PDF文件以
HttpResponseMessage
的形式返回。请注意,我在
response.Content.Headers.ContentDisposition.filename
上指定了文件名:

ASP.NET WebAPI

[Route("")]
public HttpResponseMessage Get([FromUri]MyType input)
{
    var pdfContent = PdfGenerator.Generate(input);

    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = pdfContent;
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = "MyCustomFileName.pdf"

    return response;
}
在AngularJS中,我使用如下方式获取文件:

$http.get("api/pdf/", {
    params: {
        "type": myObject
    },
    responseType: 'arraybuffer'
}).then(function (results) {
    var data = results.data;

    var file = new Blob([data], { type: 'application/pdf' });
    saveAs(file, 'filename.pdf');
}, function (results) {
    console.log(results);
});

它可以正常工作,但我在WebAPI和JavaScript上都定义了文件名。有没有一种方法,我可以在JavaScript的
结果
变量中检索WebAPI中定义的文件名?

通过
$http
方法返回的承诺作为参数传递给具有以下属性()的对象:

  • 数据{string | Object}–使用转换函数转换的响应体
  • 状态–{number}–响应的HTTP状态代码
  • headers–{function([headerName])}–Header getter函数
  • config–{Object}–用于生成请求的配置对象
  • statusText–{string}–响应的HTTP状态文本

因此
results.headers('Content-Disposition')
将为您提供
Content-Disposition
标题的值。您必须进行一些简单的解析才能获得实际的文件名。

上述解决方案在Chrome中不起作用,因为它只返回标题
缓存控制
内容类型
。下面是我的帖子,了解更多细节。前面的评论是错误的,因为从链接问题的答案中可以明显看出,问题中的问题不是Chrome,而是请求是CORS,需要明确的权限才能访问标题。