Symfony2:使用Ajax和jQuery上载文件 [英] Symfony2: Uploads a file using Ajax and jQuery
问题描述
我有一个Symfony2应用程序,其格式为文件类型字段.我需要在那里上传学生的图像,因此我帮助了此文档:如何上载文件
I have a Symfony2 application with a form where a file type field. I need to upload an image of a student there, so I helped this documentation: How to Upload Files
这是我的代码:
控制器:
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;
}
formtype:
//...
->add('photo', 'file', array('required' => false))
//...
JavaScript:
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控制器中使用它.
The problem I have now is I have to do it with an Ajax request, but do not know how to send that file field and it can be used then in Symfony controller.
我看过一些FormData()
,但是不知道如何使用.
I have seen some FormData()
, but do not know how it is used.
你能帮我吗?
推荐答案
我已经解决了代码更改:
I've solved changing in my code:
-
data: new FormData($(this)[0])
而不是data: $ (this).serialize()
添加ajax请求:
processData: false,
contentType: false,
cache: false,
文件已正确发送
这篇关于Symfony2:使用Ajax和jQuery上载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!