display images from the database JAVA

Discussão em 'Angular' iniciado por Roxana, Março 12, 2025.

  1. Roxana

    Roxana Guest

    I have a database that stores the image in a blob column. I can upload the image to the database, but it doesn't display it. The first is the error when I want to display all the images and the second when I want to add a new image. The error appears but it is loaded into the database. errors dashboard.component.ts:92 ERROR HttpErrorResponse {headers: _HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'http://localhost:8083/api/user/92/imagini', ok: false..... ERROR HttpErrorResponse {headers: _HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'http://localhost:8083/api/user/92/imagine', ok: false..... This is code from java:

    @GetMapping("/{id}/imagini")
    public ResponseEntity<List<String>> getUserImages(@PathVariable Long id) {
    List<Imagine> imagini = imagineService.getAllImaginIByIdUser(id);
    if (imagini.isEmpty()) {
    return ResponseEntity.notFound().build();
    }

    List<String> imageDataList = imagini.stream()
    .map(img -> Base64.getEncoder().encodeToString(img.getImagine()))
    .collect(Collectors.toList());

    return ResponseEntity.ok().body(imageDataList);
    }



    @PostMapping("/{id}/imagine")
    public ResponseEntity<String> uploadImage(@PathVariable Long id, @RequestParam("file") MultipartFile file) throws IOException {
    Optional<User> userOptional = userRepository.findById(id);
    if (!userOptional.isPresent()) {
    return ResponseEntity.notFound().build();
    }

    User user = userOptional.get();
    Imagine userImage = new Imagine();
    userImage.setUser(user);
    userImage.setImagine(file.getBytes()); // Dacă salvezi în DB
    imagineRepository.save(userImage);
    System.out.println("Uploading image for user: " + id);
    return ResponseEntity.ok("Imagine încărcată cu succes!");
    }



    The class for image
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Lob
    private byte[] imagine;

    @ManyToOne
    @JoinColumn(name="user_id")
    private User user


    this is code from angular:

    imagini: string[] = [];
    onFileSelected(event: any) {
    this.selectedFiles = Array.from(event.target.files);
    }
    uploadImage() {
    this.selectedFiles.forEach(file => {
    let id: string | null = localStorage.getItem("id");
    let userId: number = id ? Number(id) : 0;
    this.userService.uploadImage(userId, file).subscribe(() => {
    this.loadUserImages();
    });
    });
    }


    loadUserImages() {
    let id: string | null = localStorage.getItem("id");
    let userId: number = id ? Number(id) : 0;

    this.userService.getUserImages(userId).subscribe((imageDataArray: any) => {
    this.imagini = imageDataArray.map((data: string) => {
    // Concatenezi prefixul pentru a specifica tipul de imagine și pentru a o face compatibilă cu src
    return `data:image/jpeg;base64,${data}`;
    });
    });
    }


    this is code from service:

    uploadImage(userId: number, file: File) {
    const formData = new FormData();
    formData.append('file', file);
    // formData.append('userId',userId.toString);
    return this.http.post(BASIC_URL+"/api/user/"+userId+"/imagine", formData);
    }

    getUserImages(userId: number) {
    const token = localStorage.getItem('token'); // presupunând că token-ul este salvat în localStorage
    const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
    return this.http.get(BASIC_URL+"/api/user/"+userId+"/imagini", { responseType: 'blob' });
    }

    Continue reading...

Compartilhe esta Página