|
@@ -0,0 +1,36 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace App\Controller;
|
|
|
+
|
|
|
+use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
|
|
+use Symfony\Component\HttpFoundation\Request;
|
|
|
+use Symfony\Component\HttpFoundation\JsonResponse;
|
|
|
+use Symfony\Component\Routing\Annotation\Route;
|
|
|
+use Symfony\Component\String\Slugger\SluggerInterface;
|
|
|
+use Symfony\Component\HttpFoundation\File\Exception\FileException;
|
|
|
+use Symfony\Component\Security\Http\Attribute\IsGranted;
|
|
|
+
|
|
|
+class ImageUploadController extends AbstractController
|
|
|
+{
|
|
|
+ #[Route('/upload-image', name: 'upload_image', methods: ['POST'])]
|
|
|
+ #[IsGranted('ROLE_AUTHOR')]
|
|
|
+ public function upload(Request $request, SluggerInterface $slugger): JsonResponse
|
|
|
+ {
|
|
|
+ $image = $request->files->get('image');
|
|
|
+
|
|
|
+ if ($image && $image->isValid()) {
|
|
|
+ $originalFilename = pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
|
|
|
+ $safeFilename = $slugger->slug($originalFilename);
|
|
|
+ $newFilename = $safeFilename.'-'.uniqid().'.'.$image->guessExtension();
|
|
|
+
|
|
|
+ try {
|
|
|
+ $image->move($this->getParameter('images_directory'), $newFilename);
|
|
|
+ $url = '/uploads/images/' . $newFilename;
|
|
|
+ return new JsonResponse(['data' => ['filePath' => $url]], JsonResponse::HTTP_OK);
|
|
|
+ } catch (FileException $e) {
|
|
|
+ return new JsonResponse(['error' => $e->getCode()]);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return new JsonResponse(['error' => $image ? JsonResponse::HTTP_UNSUPPORTED_MEDIA_TYPE : JsonResponse::HTTP_BAD_REQUEST]);
|
|
|
+ }
|
|
|
+}
|