69 lines
2.1 KiB
PHP
69 lines
2.1 KiB
PHP
<?php
|
|
/**
|
|
* POST /api/lab/upload_nota_imagen.php
|
|
* Sube una imagen adjunta a una nota libre de domicilio.
|
|
*
|
|
* POST multipart/form-data con campo 'file'
|
|
* Devuelve: { success, imagen_path, file_size }
|
|
*/
|
|
require_once __DIR__ . '/../../config/config.php';
|
|
require_once __DIR__ . '/../../classes/Database.php';
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('X-Content-Type-Options: nosniff');
|
|
|
|
requireAuthentication();
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
|
|
exit;
|
|
}
|
|
|
|
if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
|
|
$code = $_FILES['file']['error'] ?? -1;
|
|
echo json_encode(['success' => false, 'error' => "No se recibió imagen (código $code)"]);
|
|
exit;
|
|
}
|
|
|
|
$file = $_FILES['file'];
|
|
|
|
// Máximo 5 MB para imágenes de notas
|
|
if ($file['size'] > 5 * 1024 * 1024) {
|
|
echo json_encode(['success' => false, 'error' => 'La imagen no puede superar 5 MB']);
|
|
exit;
|
|
}
|
|
|
|
// Validar MIME real (solo imágenes)
|
|
$allowedMimes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
|
|
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
|
$mime = finfo_file($finfo, $file['tmp_name']);
|
|
finfo_close($finfo);
|
|
|
|
if (!in_array($mime, $allowedMimes, true)) {
|
|
echo json_encode(['success' => false, 'error' => "Tipo de archivo no permitido ($mime). Solo imágenes."]);
|
|
exit;
|
|
}
|
|
|
|
// Extensión segura
|
|
$mimeToExt = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'image/gif' => 'gif'];
|
|
$ext = $mimeToExt[$mime] ?? 'jpg';
|
|
$newName = 'nota_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
|
|
|
|
$uploadDir = __DIR__ . '/../../uploads/media';
|
|
if (!is_dir($uploadDir)) {
|
|
@mkdir($uploadDir, 0755, true);
|
|
}
|
|
$destPath = realpath($uploadDir) . '/' . $newName;
|
|
|
|
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
|
|
echo json_encode(['success' => false, 'error' => 'Error al guardar el archivo en el servidor']);
|
|
exit;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'imagen_path' => $newName,
|
|
'file_size' => $file['size'],
|
|
]);
|