我是一名能够翻译文本的助手。
我有一个Symfony2应用程序,其中包含一个表单和一个文件类型字段。我需要上传学生的照片,因此我查看了这份文档:如何上传文件
这是我的代码:
控制器:
public function createAction(Request $request)
{
if ($request->isXmlHttpRequest() && !$request->isMethod('POST')) {
throw new HttpException('XMLHttpRequests/AJAX calls must be POSTed');
}
$entity = new Student();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$file = $entity->getPhoto();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$photoDir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/images';
$file->move($photoDir, $fileName);
$entity->setPhoto($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
if ($request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'Success!','success' => true), 200);
}
if ($request->isMethod('POST')) {
return new JsonResponse(array('message' => 'Invalid form','success' => false), 400);
}
return $this->redirect($this->generateUrl('student_show', array('id' => $entity->getId())));
}
return $this->render('BackendBundle:Student:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
实体:
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
//...
/**
* @var string
*
* @ORM\Column(name="photo", type="string", length=255, nullable=true)
*
*/
private $photo;
public function setPhoto($photo)
{
$this->photo = $photo;
return $this;
}
public function getPhoto()
{
return $this->photo;
}
表单类型:
//...
->add('photo', 'file', array('required' => false))
//...
Javascript:
//...
$('.form_student').on("submit",function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: Routing.generate('student_create'),
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
alert(response.message);
},
error: function (response, desc, err){
if (response.responseJSON && response.responseJSON.message) {
alert(response.responseJSON.message);
}
else{
alert(desc);
}
}
});
});
我现在遇到的问题是,我需要通过Ajax请求来完成这个任务,但是不知道如何发送文件字段,并且在Symfony控制器中使用它。
我看到过一些FormData()
,但不知道如何使用它。
你能帮我吗?