簡體   English   中英

"如何從服務器響應角度 2 中讀取內容處置標頭"

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

我無法找到如何從 angular 2 文檔中的內容配置中讀取文件名。 有人可以指導從服務器讀取 Angular 2內容標頭<\/a>中的標頭嗎

"

使用新的 Angular Http,您可以在服務代碼中嘗試以下操作。

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

並使用以上作為

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

此外,在服務器端,需要設置以下標頭作為響應。 'Access-Control-Expose-Headers': 'Content-Disposition'

就像在 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);

對於那些抱怨最佳解決方案不起作用並且標題中只有內容類型的人,您需要設置 'Access-Control-Expose-Headers': 'Content-Disposition' ON SERVER SIDE。 我正在使用 asp.net core,然后我必須執行以下操作。

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

你可以在這里嘗試這種代碼。

注意:不要使用地圖

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');
});

在 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);
        });

但主要是我們需要在API中指定Access-Control-Expose-Header ,如下所示,

注意:最后一行是必填的

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");

使用 Angular 9 和 Expresss

需要在 Express 中允許此標頭

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

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

在 Angular 7 中,up-voted 方法不起作用,你需要這樣做:

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

請查找 Angular 官方文檔以獲取更多詳細信息: https : //angular.io/guide/http#reading-the-full-response

並確保“Content-Disposition”像@mslugx 回答一樣公開

從響應頭中獲取文件名。

(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, '')
}

(文件在瀏覽器中以二進制格式保存。文件名在客戶端的 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 請求僅公開 6 個標頭:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM