0
votes

When I @GET the product, the images of the products are not visible and it throws error GET http://localhost:3000/assets/imagename.png 404 (Not Found). I saw the Network request and I found that the images are returning to frontend from NestJs server, but the type is JSON with 404. I've read other answers,but they are for direct images, while here I'm dealing with images that are path mapped with products. Somebody tell me how to convert that JSON OR text/html response into actual image that is uploaded to server.

enter image description here

NestJs: Image Upload

@Controller('images')
export class ImagesController {
  static imageUrl: string;
  constructor(private readonly bookservice: BooksService) {}

  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './assets/',
        filename: (req, file, cb) => {
          const filename: string = Array(10)
            .fill(null)
            .map(() => Math.round(Math.random() * 16).toString(16))
            .join('');
          return cb(null, `${filename}${extname(file.originalname)}`);
        },
      }),
    }),
  )
  async uploadFile(@UploadedFile() file: Express.Multer.File, @Request() req) {
    console.log(file);
    return this.imageUrl(file);
  }

  private imageUrl(file: Express.Multer.File) {
    ImagesController.imageUrl = `./assets/${file.originalname}`;
    return ImagesController.imageUrl;
  }
}

Angular: api.service.ts

public getallbooks() {
    return this.httpclient.get<Book[]>(`${this.API_SERVER}/books`);
  }
  public async addbooks(books: Book) {
    return this.httpclient.post<Book>(`${this.API_SERVER}/books`, books);
  }

Angular: uploading products with image

export class AdbooksComponent implements OnInit {
  imagedata?: string;
  book!: Book;
  AddbookForm = new FormGroup({
    bid: new FormControl(''),
    name: new FormControl(''),
    author: new FormControl(''),
    price: new FormControl(''),
    genres_name: new FormControl(''),
    coverimage: new FormControl('', {
      validators: [Validators.required],
    }),
  });
  constructor(
    private readonly apiService: ApiService,
    private readonly router: Router,
    private readonly http: HttpClient
  ) {}

  ngOnInit() {}
  async addall() {
    this.addfile();
    this.addbooks();
    this.AddbookForm.reset();
    // this.imagedata = '';
  }
  async addfile() {
    let formData = new FormData();
    formData.set(
      'file',
      this.AddbookForm.value.coverimage,
      this.AddbookForm.value.coverimage.name
    );
    this.http
      .post('http://localhost:3000/images/upload', formData, {
        responseType: 'blob',
      })
      .subscribe((res) => {});
  }
  async addbooks() {
    (await this.apiService.addbooks(this.AddbookForm.value)).subscribe(
      (res) => {
        console.log(res);
      }
    );
  }

  async uploadimage(event: any) {
    const file = event.target.files[0];
    this.AddbookForm.patchValue({ coverimage: file });
    const allowedMimeTypes = ['image/png', 'image/jpeg', 'image/jpg'];
    this.AddbookForm.get('coverimage')?.updateValueAndValidity();
    if (file && allowedMimeTypes.includes(file.type)) {
      const reader = new FileReader();
      reader.onload = () => {
        this.imagedata = reader.result as string;
      };
      reader.readAsDataURL(file);
      console.log(file);
    }
  }
}

Angular:Showing all products

 ngOnInit() {
    this.apiService.getallbooks().subscribe((data) => {
      this.results = data;
      console.log(this.results);
    });
}

Angular : Showing All products html

<div class="grid" *ngFor="let result of results">
      <div class="blog-card spring-fever" style="padding: 0.5rem; z-index: 100">
        <img
          class="image"
          src="http://localhost:3000/{{ result.coverimage }}"
          alt=""
          height="400px"
          width="250px"
          style="border: 1px solid red"
        />