如何中检索在JavaScript中的Htt presponseMessage文件名 [英] How to retreive HttpResponseMessage FileName in JavaScript

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

问题描述

我有这种方法的WebAPI,带有一个自定义对象的MyType 作为输入,并生成基于PDF文件。 PDF文件返回为一个的Htt presponseMessage 。请注意,我指定的文件名 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的文件名。有没有一种方法,我可以检索在结果的WebAPI定义文件名用JavaScript 变量?

推荐答案

$ HTTP 的方法返回的承诺是作为参数传递具有以下属性的对象(< A HREF =htt​​ps://docs.angularjs.org/api/ng/service/$http相对=nofollow> REF ):

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


      
  • 数据 - {字符串|对象} - 与变换函数变换的响应体

  •   
  • 状态 - {数} - 响应的HTTP状态code

  •   
  • 标题 - {功能([headerName])} - 头getter函数

  •   
  • 配置 - {}对象 - 这是用来生成请求的配置对象

  •   
  • 状态文本 - {string}里 - 响应的HTTP状态文字

  •   

所以 results.headers('内容处置')的意志带给你的价值内容处置头。你将不得不做一些琐碎的分析来获得实际的文件名。

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中的Htt presponseMessage文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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