简体   繁体   English

"如何从服务器响应角度 2 中读取内容处置标头"

[英]how to read content-disposition headers from server response angular 2

I am unable to find, how to read filename from content disposition in angular 2 documentation.我无法找到如何从 angular 2 文档中的内容配置中读取文件名。 Can someone guide read the headers from server in angular 2 content headers<\/a>有人可以指导从服务器读取 Angular 2内容标头<\/a>中的标头吗

"

With new Angular Http, one can try the following in the Service code.使用新的 Angular Http,您可以在服务代码中尝试以下操作。

  downloadLink(): Observable<HttpResponse<Blob>> {
    return this.http.get<Blob>(this.someURL, {
      observe: 'response',
      responseType: 'blob' as 'json'
    });
  }

And use the above as并使用以上作为

 this.someService
  .downloadLink()
  .subscribe(
    (resp: HttpResponse<Blob>) => {
      console.log(resp.headers.get('content-disposition'));
      data = resp.body
    });

Also, on the server side, one needs to set the following header in response.此外,在服务器端,需要设置以下标头作为响应。 'Access-Control-Expose-Headers': 'Content-Disposition'

Like in Java Spring Boot one can do the same using就像在 Java Spring Boot 中一样,可以使用

    final HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=1.xlsx");
    headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);

To those complaining that the best solution is not working, and only content-type is in the headers, you need to set 'Access-Control-Expose-Headers': 'Content-Disposition' ON SERVER SIDE.对于那些抱怨最佳解决方案不起作用并且标题中只有内容类型的人,您需要设置 'Access-Control-Expose-Headers': 'Content-Disposition' ON SERVER SIDE。 I am using asp.net core, then I have to do the following.我正在使用 asp.net core,然后我必须执行以下操作。

app.UseCors(builder =>
                builder.WithOrigins(originsAllowed.ToArray())
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithExposedHeaders("Content-Disposition")

You can try this kind of code here.你可以在这里尝试这种代码。

Note: Do not use map注意:不要使用地图

this.http.post(URL, DATA)
  .subscribe((res) => {
     var headers = res.headers;
     console.log(headers); //<--- Check log for content disposition
     var contentDisposition= headers.get('content-disposition');
});

In angular, we can read File Name like as show below,在 angular 中,我们可以读取文件名,如下所示,

  this.http.post(URL, DATA).subscribe(
        (res) => {
            var contentDisposition = res.headers.get('content-disposition');
            var filename = contentDisposition.split(';')[1].split('filename')[1].split('=')[1].trim();
            console.log(filename);
        });

But the main thing is that we need to specify Access-Control-Expose-Header in API as shown below,但主要是我们需要在API中指定Access-Control-Expose-Header ,如下所示,

Note: The last line is mandatory注意:最后一行是必填的

FileInfo file = new FileInfo(FILEPATH);

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = file.Name
};
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

With Angular 9 and Expresss使用 Angular 9 和 Expresss

Need to Allow this header in Express需要在 Express 中允许此标头

res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');

Angular

this.http.get(url, { observe: 'response', responseType: 'blob' as 'json' })
.subscribe((res: any) => {
    console.log(res.headers.get('content-disposition'));
});

In Angular 7 the up-voted method don't work, you need to do it like this :在 Angular 7 中,up-voted 方法不起作用,你需要这样做:

const responseHeaderFilename = response.headers.get('content-disposition');

Please find Angular official docs for more details: https://angular.io/guide/http#reading-the-full-response请查找 Angular 官方文档以获取更多详细信息: https : //angular.io/guide/http#reading-the-full-response

and also make sure that the "Content-Disposition" is exposed as in @mslugx answer并确保“Content-Disposition”像@mslugx 回答一样公开

To get the filename from response header.从响应头中获取文件名。

(data)=>{  //the 'data' is response of file data with responseType: ResponseContentType.Blob.
    let filename = data.headers.get('content-disposition').split(';')[1].split('=')[1].replace(/\"/g, '')
}

(file gets saved in binary format in the browser. the filename is in client's Network/header/Content-Disposition, we need to fetch the filename) (文件在浏览器中以二进制格式保存。文件名在客户端的 Network/header/Content-Disposition 中,我们需要获取文件名)

In Server-side code:
node js code-
    response.setHeader('Access-Control-Expose-Headers','Content-Disposition');
    response.download(outputpath,fileName);   

In client-side code:
1)appComponent.ts file
import { HttpHeaders } from '@angular/common/http';
this.reportscomponentservice.getReportsDownload(this.myArr).subscribe((event: any) => {
 var contentDispositionData= event.headers.get('content-disposition');
 let filename = contentDispositionData.split(";")[1].split("=")[1].split('"')[1].trim()
 saveAs(event.body, filename); 
});

2) service.ts file
import { HttpClient, HttpResponse } from '@angular/common/http';
getReportsDownload(myArr): Observable<HttpResponse<Blob>> {
 console.log('Service Page', myArr);
 return this.http.post(PowerSimEndPoints.GET_DOWNLOAD_DATA.PROD, myArr, {
  observe: 'response',
  responseType: 'blob'
 });
}

CORS requests only expose 6 headers : CORS 请求仅公开 6 个标头:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法在Angular4 GET响应中查看“Content-Disposition”标头 - Unable to view 'Content-Disposition' headers in Angular4 GET response 如何从Response标头中的“ content-disposition”中获取文件名? - How can i get file name inside “content-disposition” from a Response headers? Angular 文件下载,名称来自内容 Content-Disposition - Angular file download with name from content Content-Disposition 无法从后端响应获取“ Content-Disposition” - Not able to get the `Content-Disposition` from backend response 即使启用 CORS 后,我也无法在客户端上访问 Response.Headers(“Content-Disposition”) - Im not able to access Response.Headers(“Content-Disposition”) on client even after enable CORS Angular 4 新的 HttpClient 内容处置标头 - Angular 4 new HttpClient content-disposition header 从跨域 http.get 请求的 ASP.NET Web API 2 响应中获取 Angular 中的特定响应标头(例如,Content-Disposition) - Get a specific response header (e.g., Content-Disposition) in Angular from an ASP.NET Web API 2 response for a cross-origin http.get request 以角度从 ASP.NET CORE api 下载 Content-Disposition - Download Content-Disposition from ASP.NET CORE api in angular 尝试在 Angular (Content-Disposition) 中上传文件时出错 - Error when trying to upload a file in Angular (Content-Disposition) 如何解决“内容处置”header 在浏览器中显示 null - how to solve 'content-disposition' header show null in browser
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM