提交 3f1fec8a 编写于 作者: 伟伟权

119. handle file upload

上级 4ae1b6bd
<?php
namespace App\Controller;
use App\Entity\FileManaged;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class ApiFileController extends AbstractController
{
public function __invoke(Request $request, EntityManagerInterface $em, string $projectDir)
{
/**@var UploadedFile $uploadedFile * */
$uploadedFile = $request->files->get('file');
if (!$uploadedFile) {
throw new BadRequestHttpException('"file" is required');
}
$newFileName = $uploadedFile->getClientOriginalName() . '_' .
substr(hash('sha1', $uploadedFile->getClientOriginalName()), 0, 8) .
'.' . $uploadedFile->getClientOriginalExtension();
$file = new FileManaged();
$file->setMimeType($uploadedFile->getMimeType());
$file->setOriginName($uploadedFile->getClientOriginalName());
$file->setFileName($newFileName);
$file->setFileSize($uploadedFile->getSize());
$file->setPath('/uploads/images/' . $newFileName);
$em->persist($file);
$em->flush();
$uploadedFile->move($projectDir . '/public/uploads/images', $newFileName);
return $file;
}
}
\ No newline at end of file
......@@ -3,6 +3,7 @@
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Controller\ApiFileController;
use App\Repository\FileManagedRepository;
use Doctrine\ORM\Mapping as ORM;
......@@ -10,7 +11,36 @@ use Doctrine\ORM\Mapping as ORM;
* @ORM\Entity(repositoryClass=FileManagedRepository::class)
* @ORM\Table(name="file")
*/
#[ApiResource]
#[ApiResource(
collectionOperations: [
'get',
'post' => [
'controller' => ApiFileController::class,
'method' => 'post',
'deserialize' => false,
'openapi_context' => [
'requestBody' => [
'content' => [
'multipart/form-data' => [
'schema' => [
'type' => 'object',
'properties' => [
'file' => [
'type' => 'string',
'format' => 'binary',
],
],
],
],
],
],
],
]
],
itemOperations: [
'get'
]
)]
class FileManaged
{
/**
......@@ -45,6 +75,8 @@ class FileManaged
*/
private $path;
private $fileUrl;
public function getId(): ?int
{
return $this->id;
......@@ -109,4 +141,22 @@ class FileManaged
return $this;
}
/**
* @return mixed
*/
public function getFileUrl()
{
return $this->fileUrl;
}
/**
* @param mixed $fileUrl
*/
public function setFileUrl($fileUrl): void
{
$this->fileUrl = $fileUrl;
}
}
<?php
namespace App\Serializer\Normalizer;
use App\Entity\FileManaged;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Serializer\Exception\CircularReferenceException;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
class FileAwareNormalizer implements NormalizerAwareInterface, ContextAwareNormalizerInterface
{
use NormalizerAwareTrait;
/**
* @var RequestStack
*/
private RequestStack $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
private const FILE_NORMALIZER_ALREADY_CALLED = 'file_normalizer_already_called';
public function supportsNormalization($data, string $format = null, array $context = [])
{
if (isset($context[self::FILE_NORMALIZER_ALREADY_CALLED]))
{
return false;
}
return $data instanceof FileManaged;
}
/**
* @param FileManaged $object
* @param string|null $format
* @param array $context
* @return array|\ArrayObject|bool|float|int|string|null
* @throws ExceptionInterface
*/
public function normalize($object, string $format = null, array $context = [])
{
$context[self::FILE_NORMALIZER_ALREADY_CALLED] = true;
$object->setFileUrl($this->requestStack->getCurrentRequest()->getSchemeAndHttpHost() . $object->getPath());
return $this->normalizer->normalize($object, $format, $context);
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册