Home > database >  How to display images in angular from mongodb
How to display images in angular from mongodb

Time:06-14

It is a very simple question for those who know angular. Since i am new to this i am struggling to get the output. I want to display image from my mongodb to my angular page. i have saved my multer images in asset folder in angular. In my books.component.ts file i am getting the books data. i am able to display my other fields except image and pdf. console log this given below.

(2) [{…}, {…}]
0: {bookFile: {…}, bookImage: {…}, _id: '62a823f5207cbb27e6e66d06', bookName: 'King Lear', bookAuthor: 'Shakespear', …}
1: {bookFile: {…}, bookImage: {…}, _id: '62a82661207cbb27e6e66d11', bookName: 'King Lear', bookAuthor: 'Shakespear', …}
length: 2
[[Prototype]]: Array(0)

this is my books.component.ts

    import { Component, OnInit } from '@angular/core';
    import { BookdataService } from 'src/app/services/bookdata.service';
    import {BooksModel} from './books.model';
    
    @Component({
      selector: 'app-books',
      templateUrl: './books.component.html',
      styleUrls: ['./books.component.css']
    })
    export class BooksComponent implements OnInit {
      title:String = 'Book List';
      books: BooksModel[]=[];
     BookImages=[]
    
      //image properties
      // imageWidth: number=50;
      // imageMargin: number=2;
      constructor( private bookdataService: BookdataService) { }
    
      ngOnInit(): void {
        this.bookdataService.getBooks().subscribe((data)=>{
          this.books=JSON.parse(JSON.stringify(data));
          console.log(this.books);
        })
      } 
    }

this is my html file

<tr *ngFor='let book of books'>
   <td>{{ book.bookName }}</td>
   <td>
      <img  src="../../../assets/images/{{book.bookImage}}" name="photo">
   </td>
   <td>{{ book.bookAuthor }}</td>
   <td>{{ book.bookCategory }}</td>
   <td>{{ book.bookDescription }}</td>
   <td>
      <button  style="cursor:pointer" style="margin-right: 20px;">Read</button>
   </td>
   <td>
      <button  style="cursor:pointer"  style="margin-right: 20px;"> Edit</button>
      <button  style="cursor:pointer"> Delete</button>
   </td>
</tr>

and thisis my model

export class BooksModel{
   constructor(
       public bookName: string,
       public bookAuthor: string,
       public bookCategory: string,
       public bookDescription: string,
       public bookImage: string,
       public bookFile: string
  
   ){}
}

my mongodb

enter image description here

enter image description here

CodePudding user response:

The problem with your code is that bookImage is an object, and you are passing it as a string in this line

<img  src="../../../assets/images/{{book.bookImage}}" name="photo">

You should pass the identifier of the image that is inside the bookImage object instead (I don't know what that is since you left it out of your question)

EDIT: Since the image data is available you have to convert it and pass it to img src.

import { DomSanitizer } from '@angular/platform-browser';

//...

constructor(private sanitizer: DomSanitizer, private bookdataService: BookdataService) { }

//...

getImageUrl(book) {
    let objectURL = 'data:image/png;base64,'   book.bookImage.data;
    return this.sanitizer.bypassSecurityTrustUrl(objectURL);
}

Then in your html, replace the <img> line with this:

<img  [src]="getImageUrl(book)" />

CodePudding user response:

When you store your images in a database, the content is send as base64 encoded. You need to decode it (duh...) to get it displayed.

I can't replay exactly what you do in an example, however this is what you should have:

HMTL

<img id="myBookImage" [src]=thumbnail style="width: 75px" >

TS

export class ImageComponent implements OnInit {
  public safeImage!: SafeUrl;
  thumbnail: any;

  constructor(private readonly sanitizer: DomSanitizer, .....) {}

  ngOnInit(){
     // get all your books first!
     this.bookImage = booksArray[0].bookImage.data;
     this.getPicture();
  }

  getPicture() {
    let reader = new FileReader();
    reader.readAsDataURL(this.bookImage);
    reader.onloadend = (() => {
       let objectURL = reader.result;
       this.thumbnail = this.sanitizer.bypassSecurityTrustResourceUrl(''   objectURL);
    });
  }
}

In your console.log you can see that bookImage is an Object and that Object contains data (the encoded image from your database).

If you want multiple images you need to do this for every book image you have using an array for instance.

  • Related