在Symfony中,管理文件上传主要包括以下几个步骤:
FormType
来定义表单类型。例如,创建一个用于上传图片的表单类型:// src/Form/Type/UploadImageType.php
namespace App\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class UploadImageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('image', null, [
'attr' => ['accept' => 'image/*'],
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => null,
]);
}
}
Controller
来处理HTTP请求。例如,创建一个用于处理文件上传的控制器:// src/Controller/UploadController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Form\Type\UploadImageType;
class UploadController extends AbstractController
{
public function uploadAction(Request $request): Response
{
$form = $this->createForm(UploadImageType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$image = $form->get('image')->getData();
try {
$directory = $this->getParameter('uploads_directory');
$fileName = md5(uniqid()).'.'.$image->guessExtension();
$image->move($directory, $fileName);
} catch (FileException $e) {
// Handle the error
}
return $this->redirectToRoute('success');
}
return $this->render('upload.html.twig', [
'form' => $form->createView(),
]);
}
}
config/routes.yaml
文件中,为上传表单和成功页面配置路由:app:
resource:
path: 'upload'
type: annotation
upload_success:
path: /upload/success
methods: GET
templates/upload.html.twig
文件中,创建一个简单的表单模板:{% extends 'base.html.twig' %}
{% block body %}
<h1>Upload an Image</h1>
{{ form_start(form) }}
{{ form_widget(form) }}
<button type="submit">Upload</button>
{{ form_end(form) }}
{% endblock %}
config/services.yaml
文件中,配置上传目录的参数:parameters:
uploads_directory: '%kernel.project_dir%/uploads'
然后,创建uploads
目录并设置相应的权限,以便Symfony可以将文件保存到该目录。
现在,当用户访问上传页面并选择一个图片文件时,表单将提交到UploadController
的uploadAction
方法,该方法将处理文件上传并将其保存到指定的目录。上传成功后,用户将被重定向到成功页面。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。