The question is published on by Tutorial Guruji team.
I have a form in angular, one of the form inputs is an image.
The form is sent to the server, if the reponse is sucess, the response should have the image as its body, so that it is available in the browser’s devtools network > preview
section.
On success, the client should render the image got back from the server.
This is the expected response preview:
And this is the actual response:
This is the code of the request to server and the handling of the response:
this.certificateService.AddCertificate(this.info).subscribe( (upload: HttpEvent<any>) => { switch (upload.type) { case HttpEventType.DownloadProgress: this.isNewPic = false; this.certificateService.SetImage(upload); break; } }, error => { } );
The issue is that as a response I get the following instead of an image:
loaded: 43094 total: 43094 type: 3
What causes this issue? and how can that be fixed?
**Edit : **
AddCertificate(item: AddCertificateModel): Observable<any> { const Url = `${this.appConfig.apiEndpoint}/Certificate/Template/Preview`; const formData: FormData = new FormData(); for (const key in item) { if (item.hasOwnProperty(key)) { if (item[key] instanceof File) { formData.append(key, item[key], item[key].name); } else if (key == 'KeywordSampleData') { formData.append(key, JSON.stringify(item.KeywordSampleData)); } else { formData.append(key, item[key]); } } } return this.httpClient .post(Url, formData, { reportProgress: true, observe: 'events' }) .pipe(map(response => response || {} as HttpEvent<any>)); }
Answer
You’re using the reportProgress
option on your request, that means that as long as the request is still in process (the response hasn’t done yet), you’ll get events that report the request status.
What happened in your code is that in the switch
statement you handle only the HttpEventType.DownloadProgress
, but this status does not represent the final response from the server. The upload.type
that you need is HttpEventType.Response
.
To get the image, add the relevant case to your code
this.certificateService.AddCertificate(this.info).subscribe( (upload: HttpEvent<any>) => { switch (upload.type) { case HttpEventType.DownloadProgress: console.log('the process is done'); break; case HttpEventType.Response: console.log('I got the image!'); this.isNewPic = false; this.certificateService.SetImage(upload); break; } }, error => { } );