在Symfony中,管理文件上傳主要包括以下幾個步驟:
FormType
來定義表單類型。例如,創(chuàng)建一個用于上傳圖片的表單類型:// 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請求。例如,創(chuàng)建一個用于處理文件上傳的控制器:// 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
文件中,創(chuàng)建一個簡單的表單模板:{% 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
文件中,配置上傳目錄的參數(shù):parameters:
uploads_directory: '%kernel.project_dir%/uploads'
然后,創(chuàng)建uploads
目錄并設(shè)置相應(yīng)的權(quán)限,以便Symfony可以將文件保存到該目錄。
現(xiàn)在,當(dāng)用戶訪問上傳頁面并選擇一個圖片文件時,表單將提交到UploadController
的uploadAction
方法,該方法將處理文件上傳并將其保存到指定的目錄。上傳成功后,用戶將被重定向到成功頁面。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。