Reputation: 3139
I am having Web API which is two years old and don't want to make changes as it is working fine in existing Knockout and polymer applications.
I am trying to work with angular and wants to display this image.
Here is my API Code
public HttpResponseMessage GetResponse()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(this.Data);
response.Content.Headers.ContentType = "image/jpeg";
return response;
}
when I go to http://localhost:6060/designs/42698 in the browser it display image. No issues.
When I am trying to access this in angular using the below code, I am getting error as shown in attached image
this.service
.getImage(this.id)
.subscribe(
(baseImage: any) => {
if (baseImage !== null) {
const objectURL = 'data:image/jpeg;base64,' + baseImage.image;
this.image = this.sanitizer.bypassSecurityTrustUrl(objectURL);
} else {
this.image = '../assets/images/placeholder.png';
}
},
error => {
this.errorMessage = error.error;
}
);
Here is getimage code
public getImage(id: number) {
const url = `http://localhost:6060/designs/42968`;
return this.http.get<any>(url)
.pipe(catchError(error => this.errorHandler(error))); }
I can see the image in Network tab in chrome developer tools but still throwing error.
After adding response type as blob, I am getting the data as attached screenshot.
Upvotes: 2
Views: 652
Reputation: 5742
Here is what you have to do
pass your response blob
file
var reader_data = new FileReader();
reader_data.readAsDataURL(your_blob_file);
reader_data.onloadend = function() {
var base64data = reader_data.result;
console.log(base64data);<--- this returns base64
this.image = this.sanitizer.bypassSecurityTrustUrl(base64data);
}
Upvotes: 0
Reputation: 1937
You need to convert your image data to a dataURL:
const fileReader = new FileReader();
fileReader.onload = (e) => this.image = e.target.result;
fileReader.readAsDataURL(new Blob([Data]));
And also make sure you set the responseType to be of type blob
in your getImage()
service like @vsoni mentioned. It should looks like this:
public getImage(id: number) {
const url = `http://localhost:6060/designs/42968`;
return this.http.get<any>(url, { responseType: "blob" })
.pipe(catchError(error => this.errorHandler(error)));
}
Than you can display the image like this:
<img [src]="image"/>
EDIT:
Try this one:
reader.onload = function() {
console.log(reader.result)
this.image = reader.result;
};
reader.readAsDataURL(yourBlobFileFromServerHere);
Upvotes: 3