63 lines
2.0 KiB
PHP
63 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\FruitImage;
|
|
use App\Models\SortingSession;
|
|
use Illuminate\Http\Request;
|
|
|
|
class FruitImageController extends Controller
|
|
{
|
|
/**
|
|
* Terima foto JPEG dari ESP32-CAM dan simpan ke MongoDB.
|
|
* POST /api/upload-foto
|
|
*
|
|
* Field multipart/form-data:
|
|
* - label : string (nama buah, contoh: "pisang matang")
|
|
* - image : file JPEG
|
|
*/
|
|
public function upload(Request $request)
|
|
{
|
|
$request->validate([
|
|
'label' => 'required|string|max:100',
|
|
'image' => 'required|file|mimes:jpeg,jpg,png|max:2048', // maks 2 MB, termasuk PNG untuk testing
|
|
]);
|
|
|
|
try {
|
|
// Ambil sesi aktif jika ada, boleh null
|
|
$activeSession = SortingSession::active()->first();
|
|
$sessionId = $activeSession ? (string) $activeSession->_id : null;
|
|
|
|
// Konversi file JPEG ke Base64
|
|
$file = $request->file('image');
|
|
$imageBase64 = base64_encode(file_get_contents($file->getRealPath()));
|
|
$imageSize = $file->getSize(); // ukuran byte asli
|
|
|
|
$record = FruitImage::create([
|
|
'session_id' => $sessionId,
|
|
'label' => $request->input('label'),
|
|
'image_base64' => $imageBase64,
|
|
'image_size' => $imageSize,
|
|
'captured_at' => now(),
|
|
]);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => 'Foto berhasil disimpan.',
|
|
'id' => (string) $record->_id,
|
|
'label' => $record->label,
|
|
'image_size' => $record->image_size,
|
|
], 201);
|
|
|
|
} catch (\Exception $e) {
|
|
\Log::error('Upload foto gagal: ' . $e->getMessage());
|
|
|
|
return response()->json([
|
|
'success' => false,
|
|
'message' => 'Gagal menyimpan foto: ' . $e->getMessage(),
|
|
], 500);
|
|
}
|
|
}
|
|
}
|