Download-Button ergänzt
This commit is contained in:
64
app/Http/Controllers/DownloadController.php
Normal file
64
app/Http/Controllers/DownloadController.php
Normal file
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class DownloadController extends Controller
|
||||
{
|
||||
public function downloadImage(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'image_path' => 'required|string',
|
||||
]);
|
||||
|
||||
$imagePath = $request->input('image_path');
|
||||
|
||||
// Check if it's a relative path and make it absolute
|
||||
if (!filter_var($imagePath, FILTER_VALIDATE_URL)) {
|
||||
$imagePath = public_path(str_replace(url('/'), '', $imagePath));
|
||||
}
|
||||
|
||||
// Validate file exists
|
||||
if (!file_exists($imagePath)) {
|
||||
Log::error("DownloadController: Image file not found at {$imagePath}");
|
||||
return response()->json(['error' => 'Image file not found.'], 404);
|
||||
}
|
||||
|
||||
// Get file info
|
||||
$fileName = basename($imagePath);
|
||||
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
|
||||
$mimeType = $this->getMimeType($fileExtension);
|
||||
|
||||
try {
|
||||
Log::info("DownloadController: Serving download for {$imagePath}");
|
||||
|
||||
// Return the file with proper headers for download
|
||||
return response()->download($imagePath, $fileName, [
|
||||
'Content-Type' => $mimeType,
|
||||
'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error("DownloadController: Error serving download: " . $e->getMessage());
|
||||
return response()->json(['error' => 'Failed to serve download.'], 500);
|
||||
}
|
||||
}
|
||||
|
||||
private function getMimeType(string $extension): string
|
||||
{
|
||||
$mimeTypes = [
|
||||
'jpg' => 'image/jpeg',
|
||||
'jpeg' => 'image/jpeg',
|
||||
'png' => 'image/png',
|
||||
'gif' => 'image/gif',
|
||||
'webp' => 'image/webp',
|
||||
'bmp' => 'image/bmp',
|
||||
'svg' => 'image/svg+xml',
|
||||
];
|
||||
|
||||
return $mimeTypes[strtolower($extension)] ?? 'application/octet-stream';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user