Я делаю Frontend и Backend в магазине, чтобы сохранить изображения каждого продукта, который у меня есть колонна Blob в таблице продуктов (не знаю, является ли это лучшим вариантом, но не знаю другого лучшего), босс говорит мне сделать внешнее приложение, чтобы добавить изображение к каждому продукту непосредственно в DB.private void addImage() {
String selected = tableView.getSelectionModel().getSelectedItem().getDescripcion();
System.out.println("Intentando añadir imagen al artículo: " + selected);
if (selected == null) {
showAlert("Error", "Seleccione un artículo primero para añadir una imagen.");
return;
}
try {
PreparedStatement pstmt = connection.prepareStatement("SELECT Imagen FROM articulos WHERE Descripción = ?");
pstmt.setString(1, selected);
ResultSet rs = pstmt.executeQuery();
if (rs.next() && rs.getString("Imagen") != null) {
showAlert("Error", "El artículo ya tiene una imagen. Use el botón 'Actualizar' para cambiarla.");
return;
}
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(
new FileChooser.ExtensionFilter("Images", "*.png", "*.jpg", "*.jpeg")
);
File file = fileChooser.showOpenDialog(null);
if (file != null) {
String base64Image = convertImageToBytes(file);
if (base64Image != null) {
pstmt = connection.prepareStatement("UPDATE articulos SET Imagen = ? WHERE Descripción = ?");
pstmt.setString(1, base64Image);
pstmt.setString(2, selected);
pstmt.executeUpdate();
System.out.println("Imagen añadida correctamente al artículo: " + selected);
displayImage(selected);
} else {
showAlert("Error", "Error al convertir la imagen");
}
}
} catch (SQLException e) {
System.out.println("Error al añadir imagen: " + e.getMessage());
showAlert("Error", "Error al añadir imagen: " + e.getMessage());
}
}
< /code>
private String convertImageToBytes(File imageFile){
byte[] imageBytes = null;
try(ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileInputStream fis = new FileInputStream(imageFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
imageBytes = baos.toByteArray();
return Base64.getEncoder().encodeToString(imageBytes);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
< /code>
In the app you just select a product from the db an select an img from your pc, here I don't have a problem the image, it saves succesfully and even shows itself if you click in the same product again, in the Spring Boot controller I get the product with its image:
@GetMapping("/ofertas")
public ResponseEntity getArticulosEnOferta() {
List articulos = ArticuloService.obtenerArticulosEnOferta();
List articulosDTO = articulos.stream().map(a -> new ArticuloDTO(
a.getId_articulo(),
a.getNombre(),
a.getPrecio_medio(),
a.isRebajado(),
a.getPrecioRebajado(),
a.getImagen() != null ? Base64.getEncoder().encodeToString(a.getImagen()) : null
)).collect(Collectors.toList());
return ResponseEntity.ok(articulosDTO);
}
< /code>
but when I'm trying to show that pic in angular, I get an error, normally a loop where the page trying to process the image, all the time I'm getting a lot of errors in the console log every second:
contacto.component.ts:88 Image failed to load:
Event {isTrusted: true, type: 'error', target: img.full-page-image, currentTarget: img.full-page-image, eventPhase: 2, …}
onImageError @ contacto.component.ts:88
ContactoComponent_div_3_Template_img_error_1_listener @ contacto.component.html:14
Zone - HTMLImageElement.addEventListener:error
ContactoComponent_div_3_Template @ contacto.component.html:14
ContactoComponent_Template @ contacto.component.html:10
XMLHttpRequest.send
loadProduct @ contacto.component.ts:40
ngOnInit @ contacto.component.ts:35
Promise.then
4429 @ main.ts:12
__webpack_exec__ @ main.ts:34
(anonymous) @ main.ts:34
(anonymous) @ main.ts:34
(anonymous) @ main.js:2
< /code>
I added some logs to see if I get the blob column from the db, and yes I get it, so the problem should be when angular is trying to process the img.
cargarProductosEnOferta() {
this.isLoading = true;
this.error = null;
this.productService.getProductosEnOferta().subscribe({
next: (productos) => {
console.log('Productos cargados:', productos.length);
this.productosEnOferta = productos;
productos.forEach((producto, index) => {
console.log(`Producto ${index + 1}:`, {
id: producto.id_articulo,
nombre: producto.nombre,
descripcion: producto.descripcion,
precio_medio: producto.precio_medio,
rebajado: producto.rebajado,
precioRebajado: producto.precioRebajado,
imagen: producto.imagen ? {
tipo: typeof producto.imagen,
longitud: producto.imagen.length,
muestra: typeof producto.imagen === 'string'
? producto.imagen.substring(0, 50) + '...'
: 'byte array'
} : 'sin imagen'
});
});
if (productos.length > 0) {
console.log('Estructura completa del primer producto:', JSON.stringify(productos[0], null, 2));
}
this.isLoading = false;
},
error: (error) => {
console.error('Error loading products:', error);
this.error = 'Error al cargar los productos';
this.isLoading = false;
}
});
}
< /code>
sanitizeBase64Image(imageData: string): SafeUrl {
if (!imageData) {
return this.sanitizer.bypassSecurityTrustUrl('assets/default-product.jpg');
}
try {
return this.sanitizer.bypassSecurityTrustUrl(imageData);
} catch (error) {
console.error('Error processing image:', error);
return this.sanitizer.bypassSecurityTrustUrl('assets/default-product.jpg');
}
}
< /code>
[style.gridTemplateColumns]="'repeat(' + calcularColumnas(productosEnOferta.length) + ', 1fr)'">
[alt]="producto.nombre"
class="product-image">
-{{calcularPorcentajeDescuento(producto)}}%
{{producto.nombre}}
{{producto.precio_medio}}€
{{producto.precioRebajado}}€
Añadir al carrito
< /code>
Probably I'm just blind and the error is obvious, but I really don't see it.
Added some logs to see if I get correctly the img from the db this is an example of a product I get:
Estructura completa del primer producto: {
"id_articulo": 1, //id from the product
"nombre": "ADAPTADOR USB WIFFI 1200 MBPS NAN0", // name of the product
"precio_medio": 12.86, //Price
"rebajado": true, //In sale
"precioRebajado": 10, //Sale price
"imagen": "data:image/jpeg;base64,LzlqLzRBQVFTa1pKUmdBQkFRQUFBUUFCQUFELzJ3QkRBQU1DQWdJQ0FnTUNBZ0lEQXdNREJBWUVCQVFFQkFnR0JnVUdDUWdLQ2drSUNRa0tEQThNQ2dzT0N3a0pEUkVORGc4UUVCRVFDZ3dTRXhJUUV3OFFFQkQvMndCREFRTURBd1FEQkFnRUJBZ1FDd2tMRUJBUUVCQVFFQkFRRUJB......... //The img chain,and yes its longer than this if anyone ask it
Подробнее здесь: https://stackoverflow.com/questions/796 ... from-mysql