-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimgService.php
66 lines (56 loc) · 2.24 KB
/
imgService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
require_once "../Context/Database.php";
class imgService {
private $conn;
public function __construct() {
$database = new Database();
$this->conn = $database->getConnection();
}
public function Consultar() {
$query = "SELECT * FROM img";
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function guardarImagen($imagen, $nombreImagen) {
$tipoImagen = strtolower(pathinfo($nombreImagen, PATHINFO_EXTENSION));
$directorio = "../archivos/";
if ($tipoImagen == "jpg" || $tipoImagen == "jpeg" || $tipoImagen == "png") {
try {
// Insertar registro vacío y obtener ID
$stmt = $this->conn->query("INSERT INTO img(Foto) VALUES('')");
$idRegistro = $this->conn->lastInsertId();
$ruta = $directorio . $idRegistro . "." . $tipoImagen;
// Actualizar con la ruta
$stmt = $this->conn->prepare("UPDATE img SET Foto = ? WHERE Id_img = ?");
$stmt->execute([$ruta, $idRegistro]);
// Almacenar la imagen
if (move_uploaded_file($imagen, $ruta)) {
return ["success" => true, "message" => "Imagen guardada exitosamente"];
} else {
return ["success" => false, "message" => "Error al guardar la imagen"];
}
} catch (PDOException $e) {
return ["success" => false, "message" => "Error en la base de datos: " . $e->getMessage()];
}
} else {
return ["success" => false, "message" => "No se aceptan archivos con el formato " . $tipoImagen];
}
}
}
// Procesar el formulario
if (!empty($_POST["btn-registrar"])) {
$imgService = new imgService();
$resultado = $imgService->guardarImagen(
$_FILES["input-imagen"]["tmp_name"],
$_FILES["input-imagen"]["name"]
);
echo "<div class='alert alert-" . ($resultado["success"] ? "info" : "danger") . "'>" .
$resultado["message"] . "</div>";
?>
<script>
history.replaceState(null, null, location.pathname);
</script>
<?php
}
?>