How to display image of an API via URL with Angular - TagMerge
3How to display image of an API via URL with AngularHow to display image of an API via URL with Angular

How to display image of an API via URL with Angular

Asked 5 months ago
1
3 answers

Based on the screenshot you posted, image is not a string, is an object, change this in your interface:

export interface Heroi {
 id: string,
 name: string,
 image: { url: string }
}
<ul *ngFor="let heroi of herois">  
    <li>
       <p>{{ heroi.id }}</p>
       <p>{{ heroi.name }}</p>
       <img  
        *ngIf="heroi.image?.url"
        [src]="heroi.image.url" 
        [alt]="heroi.name">
    </li>
</ul>

Source: link

0

Car Component Codes
getCars(){
this.carService.getCars().subscribe(response => {
  this.cars = response.data;
  this.dataLoaded = true;
  this.setCoverImage(this.cars);
});
}  
getCarImages(){
      this.carImageService.getCarImages().subscribe(response => {
          this.carImages = response.data;
        })
      }


 setCoverImage(carList: Car[]){
     carList.forEach(item => {
       this.carImageService.getCarImagesById(item.carId).subscribe(response => {
         item.imagePath = "http://localhost:4200/" + response.data[0].imagePath;
       })
      })
    }
Car Image Service Codes
export class CarImageService {
  apiUrl = "https://localhost:44327/api/";
  constructor(private httpClient : HttpClient) { }

  getCarImages() : Observable<ListResponseModel<CarImage>>{
    let newPath = this.apiUrl + "carimages/getall";
    return this.httpClient.get<ListResponseModel<CarImage>>(newPath);
  }

  getCarImagesById(carId: number) : Observable<ListResponseModel<CarImage>>{
    let newPath = this.apiUrl + "carimages/getimagesbycarid?id=" + carId;
    return this.httpClient.get<ListResponseModel<CarImage>>(newPath);
  } 
}
In your client side code property bind the src property of Image tag to show the image
setCoverImage(carList: Car[]){
     carList.forEach(item => {
       this.carImageService.getCarImagesById(item.carId).subscribe(response => {
         item.imagePath = response;
       })
      })
    }
In html
<image
[src]="item.imagePath"
/>

Source: link

0

Here are the changes you need to make:
public Path fetchProfilePhotoByUserId(String userId) throws ImageRetrievalException {
        Path imagePath = null;
        
        Path rootLocation = Paths.get(getRootLocationForUserProfileImageUpload(userId));
        LOG.debug("Fetching profile image from " + rootLocation.toString());

        try {
            if (rootLocation.toFile().exists()) {
                Iterator<Path> iterator = Files.newDirectoryStream(rootLocation).iterator();
                
                if (iterator.hasNext()) {
                    imagePath = iterator.next();                
                    LOG.debug("File name is " + imagePath);
                }            
            }
        } catch (IOException ie) {
            throw new ImageRetrievalException(ie.getMessage());
        }
        
        return imagePath;
    }
    
    
    private void deleteAllFilesInDirectory(Path rootLocation) {
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(rootLocation)) {
            directoryStream.forEach(path -> {
                path.toFile().delete();
            });
        } catch (IOException ie) {
            LOG.error("Problem trying to delete files in " + rootLocation.toString());
        }
    }
    
    
    public void saveProfilePhoto(MultipartFile file, User user) throws MissingFileException, FileTooLargeException, CopyFileException {
        validateFile(file, maxFileUploadSize);
        Path rootLocation = Paths.get(getRootLocationForUserProfileImageUpload(user));
        deleteAllFilesInDirectory(rootLocation);
        saveFile(file, user, rootLocation);
    }

    
    private void saveFile(MultipartFile file, User user, Path rootLocation) throws CopyFileException {
        try (InputStream is = file.getInputStream()) {
            String newFileName = getNewFileName(file, user);
            Files.copy(is, rootLocation.resolve(newFileName));
        } catch (IOException ie) {
            LOG.error("Problem uploading file!", ie);
            throw new CopyFileException("Failed to upload!");
        }
    }
Now it's time for a new controller: UserController.
package com.careydevelopment.ecosystem.user.controller;

import java.nio.file.Files;
import java.nio.file.Path;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.careydevelopment.ecosystem.user.util.FileUtil;
import com.careydevelopment.ecosystem.user.util.SecurityUtil;

@CrossOrigin(origins = "*")
@RestController
public class UserController {
    
    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    
    @Autowired
    private SecurityUtil securityUtil;
    
    @Autowired
    private FileUtil fileUtil;
    
    
    @GetMapping("/user/{userId}/profileImage")
    public ResponseEntity<?> getProfileImage(@PathVariable String userId) {        
        try {
            Path imagePath = fileUtil.fetchProfilePhotoByUserId(userId);
            
            if (imagePath != null) {
                LOG.debug("Getting image from " + imagePath.toString());
                
                ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(imagePath));
                
                return ResponseEntity
                        .ok()
                        .contentLength(imagePath.toFile().length())
                        .contentType(MediaType.IMAGE_JPEG)
                        .body(resource);                    
            } else {
                LOG.debug("Profile photo not found for user " + userId);
                return ResponseEntity.status(HttpStatus.OK).build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
Before you do that, though, you need to update UserService.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from '../../models/user';

@Injectable({ providedIn: 'root' })
export class UserService {

  private _user: User = null;

  constructor(private http: HttpClient) { }

  get user(): User {
    return this._user;
  }

  set user(user: User) {
    this._user = user;
  }

  fetchProfileImage(userId: string): Observable<Blob> {
    let url = "http://localhost:8080/user/" + userId + "/profileImage";
    console.log("Profile image URL is " + url);

    return this.http.get(url, { responseType: 'blob' });
  }
}
Now it's time to update ProfileImageComponent. Here are the changes you need to make:
currentFileUpload: UploadedImage;
  changeImage: boolean = false;
  uploading: boolean = false;
  imageToShow: any = null;
  user: User = null;
  showSpinner: boolean = true;

  constructor(private uploadService: UploadFileService, private userService: UserService,
    private imageService: ImageService, private alertService: AlertService) { }

  ngOnInit() {
    this.user = this.userService.user;

    this.userService.fetchProfileImage(this.user.id)
      .subscribe(image => this.createImage(image),
        err => this.handleImageRetrievalError(err));
  }

  private handleImageRetrievalError(err: Error) {
    console.error(err);
    this.showSpinner = false;
    this.alertService.error("Problem retrieving profile photo.");
  }

  private createImage(image: Blob) {
    if (image && image.size > 0) {
      let reader = new FileReader();

      reader.addEventListener("load", () => {
        this.imageToShow = reader.result;
        this.showSpinner = false;
      }, false);

      reader.readAsDataURL(image);
    } else {
      this.showSpinner = false;
    }
  }
Now take a look at the HTML associated with the component. Edit profile-image.component.html.
<div fxFlex fxLayout="column" fxLayoutGap="0px" class="route-content">
  <div fxLayout="row wrap">
    <div fxLayout="column">
      <div>
        <h4>Profile Image</h4>
        

Upload a square image no smaller than 200x200. Then click the <strong>Save Image</strong> button to save it.

</div> <div class="alert-section"> <alert></alert> </div> <div class="upload-image-box"> <div style="text-align: center"> <app-image-uploader [showSpinner]="showSpinner" [image]="imageToShow" (uploadedImage)="onUploadedImage($event)"></app-image-uploader> </div> <div *ngIf="!uploading" style="text-align:center"> <button mat-raised-button color="primary" [disabled]="!currentFileUpload" (click)="upload()">Save Image</button> </div> <div *ngIf="uploading"> <mat-spinner [diameter]="50" class="center-div"></mat-spinner> </div> </div> </div> </div> </div>

Source: link

Recent Questions on angular

    Programming Languages