/** * @Route("/admin/slideshow/picture/upload", name="jc_slideshow_bo_picture_upload") */ public function uploadPictureAction(Request $request) { $entityManager = $this->getDoctrine()->getManager(); try { // Create new picture $picture = new Picture(); // Set slideshow + rank $slideshowId = $request->request->get('slideshowId'); $slideshow = $entityManager->getRepository(Slideshow::class)->find($slideshowId); $picture->setSlideshow($slideshow); $picture->setRank($entityManager->getRepository(Picture::class)->getMaxRankForSlideshow($slideshow) + 1); // Process file upload $file = $request->files->get('file'); $relativeFolderPath = $this->getParameter('jc_slideshow.root_path') . '/slideshow_' . $slideshowId; $absoluteFolderPath = $this->getParameter('kernel.root_dir') . '/../web' . $relativeFolderPath; // Create folder if necessary if (!is_dir($absoluteFolderPath)) { mkdir($absoluteFolderPath); } // For picture's name => use file name without extension $originalName = $file->getClientOriginalName(); $dotIndex = strrpos($originalName, '.'); $name = substr($originalName, 0, $dotIndex); $extension = substr($originalName, $dotIndex + 1); // For picture's file => use unique name and move file into appropriate folder $uniqueFileName = $this->getUniqueFileNameForPicture($absoluteFolderPath, $extension); $file->move($absoluteFolderPath, $uniqueFileName); $picture->setName($name); $picture->setPictureUrl($relativeFolderPath . '/' . $uniqueFileName); // Set picture size $pictureSize = getimagesize($this->getParameter('kernel.root_dir') . '/../web' . $picture->getPictureUrl()); $picture->setWidth($pictureSize[0]); $picture->setHeight($pictureSize[1]); // Save new picture $entityManager->persist($picture); $entityManager->flush(); return new JsonResponse(array('success' => true, 'id' => $picture->getId(), 'name' => $picture->getName(), 'rank' => $picture->getRank(), 'url' => $picture->getPictureUrl())); } catch (Exception $e) { return new JsonResponse(array('success' => false, 'message' => 'Erreur lors de la création de l\'image')); } }
/** * Allows to upload files defined in picture object. * @param Picture $picture */ private function processUpload($picture) { $relativeFolderPath = $this->container->getParameter('jc_slideshow.root_path') . '/slideshow_' . $picture->getSlideshow()->getId(); $absoluteFolderPath = $this->container->getParameter('kernel.root_dir') . '/../web' . $relativeFolderPath; // Create folder if necessary if (!is_dir($absoluteFolderPath)) { mkdir($absoluteFolderPath); } // If main picture is defined => process upload if (null !== $picture->getPictureFile()) { $pictureName = $picture->getPictureFile()->getClientOriginalName(); // Move file in userfiles folder + save new URL $picture->getPictureFile()->move($absoluteFolderPath, $pictureName); $picture->setPictureUrl($relativeFolderPath . '/' . $pictureName); } }