Skip to content

Instantly share code, notes, and snippets.

@kurozumi
Created February 25, 2019 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurozumi/3b877ddcefa134844945374cad5a5e76 to your computer and use it in GitHub Desktop.
Save kurozumi/3b877ddcefa134844945374cad5a5e76 to your computer and use it in GitHub Desktop.
ImageController
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use App\Service\FileUploader;
class FileController extends AbstractController {
/**
* @Route("/image/add", name="image_add", methods={"POST"})
*/
public function addImage(Request $request, FileUploader $fileUploader) {
if (!$request->isXmlHttpRequest()) {
throw new BadRequestHttpException();
}
$images = $request->files->get('add_images');
$allowExtensions = ['gif', 'jpg', 'jpeg', 'png'];
$files = [];
if (isset($images["image"])) {
$image = $images["image"];
//ファイルフォーマット検証
$mimeType = $image->getMimeType();
if (0 !== strpos($mimeType, 'image')) {
throw new UnsupportedMediaTypeHttpException();
}
// 拡張子
$extension = $image->getClientOriginalExtension();
if (!in_array($extension, $allowExtensions)) {
throw new UnsupportedMediaTypeHttpException();
}
$files[] = $fileUploader->upload($image);
}
return $this->json(['files' => $files], 200);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment