gpt4 book ai didi

javascript - 如何在 JavaScript 中检索 HttpResponseMessage 文件名

转载 作者:数据小太阳 更新时间:2023-10-29 04:14:45 33 4
gpt4 key购买 nike

我有这个 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 中,我使用 FileSaver.js 获取文件像这样:

$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 的 results 变量中检索在 WebAPI 中定义的文件名?

最佳答案

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

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

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

关于javascript - 如何在 JavaScript 中检索 HttpResponseMessage 文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29071785/

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