У меня есть база данных, которая хранит изображение в столбце Blob. Я могу загрузить изображение в базу данных, но оно не отображает его. Ошибка появляется, но загружается в базу данных. < /P>
ошибки < /p>
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.....
< /code>
Это код Java: < /p>
@GetMapping("/{id}/imagini")
public ResponseEntity getUserImages(@PathVariable Long id) {
List imagini = imagineService.getAllImaginIByIdUser(id);
if (imagini.isEmpty()) {
return ResponseEntity.notFound().build();
}
List imageDataList = imagini.stream()
.map(img -> Base64.getEncoder().encodeToString(img.getImagine()))
.collect(Collectors.toList());
return ResponseEntity.ok().body(imageDataList);
}
< /code>
@PostMapping("/{id}/imagine")
public ResponseEntity uploadImage(@PathVariable Long id, @RequestParam("file") MultipartFile file) throws IOException {
Optional 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!");
}
< /code>
Класс для изображения < /p>
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Lob
private byte[] imagine;
@ManyToOne
@JoinColumn(name="user_id")
private User user
< /code>
Это угловой код: < /p>
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();
});
});
}
< /code>
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}`;
});
});
}
< /code>
Это код службы: < /p>
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' });
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... e-database