Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4 show image from server

Tags:

angular

I want to show an image in img tag : i am doing it that way

Component

this.file.url=this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.file.url));

Template

<img [src]="file.url">

I am getting this error

ERROR TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
like image 330
ketimaBU Avatar asked Aug 16 '17 18:08

ketimaBU


People also ask

How to display img in angular?

Once you have put all the required images in the assets directory open the specific component typescript (. ts) file where you want to serve the image. Now you can add the URL of the image in a variable within the constructor so that it is initialized upon component creation.

How to add images to an angular application?

This tutorial shows multiple examples in Angular, One example is to load images using the img tag Another example is to bind the src attribute to the assets folder. Normally, Images are placed in the src/assets folder in the Angular application.

Which tag is used to display an image on an angular?

The Img tag is used to display an image on an angular application. It is declared in the HTML template file. src contains the absolute path of images that referred from the HTML file alt contains string content to display on image for SEO purpose

Why are my images not displaying correctly in angular?

If images do not display correctly, check src/assets folder is included inside the assets attribute in the angular.json file of your angular application. Check path relevant HTML file location with the assets folder

Where can I find the code for Spring Boot and angular?

If you'd rather just get the code, you can do so on GitHub ( here for the Spring Boot service and here for the Angular code). Otherwise, pull up a rock and sit a while. Remember: if you're having problems running the Angular app locally, be sure to check the README.


1 Answers

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

Here is an working example:

Create image.service.ts and put following code:

    getImage(imageUrl: string): Observable<File> {
        return this.http
            .get(imageUrl, { responseType: ResponseContentType.Blob })
            .map((res: Response) => res.blob());
    }

Now you need to create some function in your image.component.ts to get image and show it in html.

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:

imageToShow: any;

createImageFromBlob(image: Blob) {
       let reader = new FileReader();
       reader.addEventListener("load", () => {
          this.imageToShow = reader.result;
       }, false);

       if (image) {
          reader.readAsDataURL(image);
       }
}

If you have more then one image, you can define imageToShow[] = [] as array. And now you can simple push reader.result to this array. For example: this.imageToShow.push(reader.result). In your template you can iterate and output this array with *ngFor="let image of imageToShow;".

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example function:

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

Now you can use your imageToShow-variable in HTML template like this:

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

I hope this description is clear to understand and you can use it in your project.

like image 117
Gregor Doroschenko Avatar answered Oct 09 '22 22:10

Gregor Doroschenko