76 lines
2.1 KiB
PHP
76 lines
2.1 KiB
PHP
<?php
|
|
require_once 'DocumentProcessor.php';
|
|
|
|
// Define diretórios
|
|
$upload_dir = __DIR__ . '/uploads/';
|
|
$processed_dir = $upload_dir . 'processed/';
|
|
|
|
// Garante que os diretórios existam
|
|
if (!file_exists($upload_dir)) {
|
|
mkdir($upload_dir, 0777, true);
|
|
}
|
|
if (!file_exists($processed_dir)) {
|
|
mkdir($processed_dir, 0777, true);
|
|
}
|
|
|
|
$response = ['success' => false, 'message' => '', 'file' => ''];
|
|
|
|
try {
|
|
// Verifica se recebeu um arquivo
|
|
if (!isset($_FILES['document'])) {
|
|
throw new Exception('Nenhum arquivo enviado');
|
|
}
|
|
|
|
$file = $_FILES['document'];
|
|
if ($file['error'] !== UPLOAD_ERR_OK) {
|
|
throw new Exception('Erro no upload: ' . $file['error']);
|
|
}
|
|
|
|
// Validação do tipo de arquivo
|
|
$allowed_types = ['image/jpeg', 'image/png'];
|
|
if (!in_array($file['type'], $allowed_types)) {
|
|
throw new Exception('Tipo de arquivo não permitido. Use JPG ou PNG.');
|
|
}
|
|
|
|
// Gera nomes únicos para os arquivos
|
|
$temp_name = uniqid() . '_' . basename($file['name']);
|
|
$upload_path = $upload_dir . $temp_name;
|
|
$output_path = $processed_dir . 'proc_' . $temp_name;
|
|
|
|
// Move o arquivo enviado
|
|
if (!move_uploaded_file($file['tmp_name'], $upload_path)) {
|
|
throw new Exception('Falha ao mover arquivo enviado');
|
|
}
|
|
|
|
// Processa o documento
|
|
$processor = new DocumentProcessor();
|
|
$result = $processor->processDocument($upload_path, $output_path);
|
|
|
|
// Prepara resposta de sucesso
|
|
$response = [
|
|
'success' => true,
|
|
'message' => 'Documento processado com sucesso',
|
|
'file' => 'uploads/processed/proc_' . $temp_name,
|
|
'original' => 'uploads/' . $temp_name
|
|
];
|
|
|
|
} catch (Exception $e) {
|
|
$response = [
|
|
'success' => false,
|
|
'message' => $e->getMessage()
|
|
];
|
|
|
|
// Limpa arquivos em caso de erro
|
|
if (isset($upload_path) && file_exists($upload_path)) {
|
|
unlink($upload_path);
|
|
}
|
|
if (isset($output_path) && file_exists($output_path)) {
|
|
unlink($output_path);
|
|
}
|
|
}
|
|
|
|
// Retorna resposta em JSON
|
|
header('Content-Type: application/json');
|
|
echo json_encode($response);
|
|
?>
|