Adatbázisban tárolhatjuk a képek útvonalát és a magukat a képeket is. Ebben a leírásban a képeket fogjuk adatbázisban tárolni és nem azok útvonalát.
A migrációs fájlban az up() metódus tartalma:
public function up(): void { Schema::create('employees', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('city'); $table->double('salary'); $table->binary('image'); $table->timestamps(); }); }
public function store(Request $request) { $path = NULL; $imageData = NULL; if($request->hasFile('image')) { $path = $request->file('image'); $imageData = file_get_contents($path); $imageBase64 = base64_encode($imageData); } $employee = new Employee; $employee->name = $request->name; $employee->city = $request->city; $employee->salary = $request->salary; $employee->image = $imageBase64; $employee->save(); return response()->json([ 'name' => $employee->name, 'success' => 'ok' ]); }
Példa:
$request->validate([ 'name' => 'required|string|max:255', 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]);
Ha képekről MIME adatokat is tárolunk, akkor semmit nem kell konvertálni kliens oldalon.
$employee = new Employee; $employee->name = $request->name; $employee->city = $request->city; $employee->salary = $request->salary; $employee->image = 'data:image/png;base64,' . $imageBase64; $employee->save();
A böngészők megjelenítik az ilyen adatot:
<img src="data:image/png;base64,iVBORw0KG... (a további képadataik)">
public function store(Request $request) { $path = NULL; $mime = NULL; $imageData = NULL; if($request->hasFile('image')) { $path = $request->file('image'); $mime = $request->file('image')->getClientMimeType(); $imageData = file_get_contents($path); $imageBase64 = base64_encode($imageData); } $employee = new Employee; $employee->name = $request->name; $employee->city = $request->city; $employee->salary = $request->salary; $employee->image = 'data:'. $mime .';base64,' . $imageBase64; $employee->save(); return response()->json([ 'name' => $employee->name, 'success' => 'ok' ]); }