Я делаю фронт и бэкэнд в ИТ -магазине, чтобы сохранить изображения каждого продукта, у меня есть столбец Blob в таблице продуктов (не знаю, является ли это лучшим вариантом, но не знаю другого лучше), босс говорит мне сделать внешнее приложение, чтобы добавить изображение в каждый продукт непосредственно в DB. < /p>
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 u just select a product from the db an select an img from your pc, here i dont have a problem the image saves succesfully and even shows itself if u click in the same product again, in the springboot controller i get the product with his 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 try to show that pic in angular i get an error, normally a loop where the page try to process the image all the time 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 try 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 im just blind and the error is obviously but i really dont see it xd.
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 ... y-mysql-db
Как я могу показать изображения в Angular из моего MySQL DB? ⇐ Javascript
Форум по Javascript
-
Anonymous
1746519477
Anonymous
Я делаю фронт и бэкэнд в ИТ -магазине, чтобы сохранить изображения каждого продукта, у меня есть столбец Blob в таблице продуктов (не знаю, является ли это лучшим вариантом, но не знаю другого лучше), босс говорит мне сделать внешнее приложение, чтобы добавить изображение в каждый продукт непосредственно в DB. < /p>
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 u just select a product from the db an select an img from your pc, here i dont have a problem the image saves succesfully and even shows itself if u click in the same product again, in the springboot controller i get the product with his 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 try to show that pic in angular i get an error, normally a loop where the page try to process the image all the time 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 try 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)'">
[i] [alt]="producto.nombre"
class="product-image">
-{{calcularPorcentajeDescuento(producto)}}%
{{producto.nombre}}
{{producto.precio_medio}}€
{{producto.precioRebajado}}€
[/i]
Añadir al carrito
< /code>
Probably im just blind and the error is obviously but i really dont see it xd.
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
Подробнее здесь: [url]https://stackoverflow.com/questions/79608191/how-i-can-show-images-in-angular-from-my-mysql-db[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия