How to check the response or status code in angular 8 for upload file to S3 Presigned URL and statusCode is 200

只愿长相守 提交于 2021-02-07 08:53:20

问题


Request to upload file:

// upload file to the pre-signed url
const httpOptions = {
 headers: new HttpHeaders({
 'Content-Disposition': 'attachment;filename=' + file.name + '',
 observe: 'response'
 })
};

this.httpClient.put(preSingedUrl, file, httpOptions)
.subscribe((response: HttpResponse<any>) => {
console.log(response); // it's returning null
});

response is always getting null, but in the network tab status is 200 OK.

access-control-allow-methods: GET, POST, OPTIONS
access-control-allow-origin: *
content-length: 1207
content-type: application/json
date: Tue, 25 Jun 2019 07:38:06 GMT
status: 200
strict-transport-security: 'max-age=31536000'
x-amz-apigw-id: someid
x-amzn-requestid: someid
x-amzn-trace-id: Root=someid;Sampled=1

How to read the status 200 OK using angular 8.


回答1:


The issue is in httpOptions, which is why you are getting response null.

If you are trying to use observe: 'response' to get the response back in subscribe, you are passing it incorrectly as a header.

It should be passed as a property of httpOptions.

To confirm the same, in the image below, the implementation of httpClient.put() in the type file http.d.ts in the package @angular/common can be seen, where observe is a property.

Additionally, in the type file http.d.ts the type of observe is a string literal type. (More on string literal types here : https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types).

So observe in httpOptions needs to be cast to this type.

So change this:

// upload file to the pre-signed url
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Disposition': 'attachment;filename=' + file.name + '',
     observe: 'response'
  })
};

To this :

// Custom type for casting
type bodyType = 'body';

// upload file to the pre-signed url
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Disposition': 'attachment;filename=' + file.name + '',
  }),
  observe: <bodyType>'response'
};


来源:https://stackoverflow.com/questions/56749149/how-to-check-the-response-or-status-code-in-angular-8-for-upload-file-to-s3-pres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!