如何在JavaScript中检索HttpResponseMessage FileName [英] How to retrieve HttpResponseMessage FileName in JavaScript

查看:312
本文介绍了如何在JavaScript中检索HttpResponseMessage FileName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've this WebAPI method, that takes a custom object MyType as input and generate a PDF based on that. The PDF-file is returned as a HttpResponseMessage. Note that I specify the filename on 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 是这样的:

In AngularJS I fetch the file using FileSaver.js like this:

$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中定义的FileName?

It works as excepted, but I'm defining the filename both on WebAPI and in the JavaScript. Is there a way, that I can retrieve the FileName defined in WebAPI in the results variable in JavaScript?

推荐答案

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

The promise returned by methods of $http are passed as argument an object with the following properties (ref):



  • data - {string | Object} - 使用转换函数转换的响应体。

  • status - {number} - 响应的HTTP状态代码。

  • headers - {function([headerName])} - Header getter function。

  • config - {Object} - 用于生成请求。

  • statusText - {string} - 响应的HTTP状态文本。

  • 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 标题。你将不得不做一些简单的解析来获得实际的文件名。

So results.headers('Content-Disposition') will gives you the value of the Content-Disposition header. You will have to do some trivial parsing to get to the actual filename.

这篇关于如何在JavaScript中检索HttpResponseMessage FileName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆