Symfony2:使用Ajax和jQuery上传文件

Jos*_*eph 7 php ajax jquery symfony

我有一个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(),
    ));
}
Run Code Online (Sandbox Code Playgroud)

实体:

   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;
   }
Run Code Online (Sandbox Code Playgroud)

formtype:

   //...

   ->add('photo', 'file', array('required' => false))

   //...
Run Code Online (Sandbox Code Playgroud)

使用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);
      }
  }
 });
});
Run Code Online (Sandbox Code Playgroud)

我现在遇到的问题是我必须使用Ajax请求,但不知道如何发送该文件字段,然后可以在Symfony控制器中使用它.

我见过一些FormData(),但不知道它是如何使用的.

你可以帮帮我吗?

Jos*_*eph 11

我已经解决了我的代码更改:

  • data: new FormData($(this)[0]) 代替 data: $ (this).serialize()

  • 添加ajax请求:

    processData: false, contentType: false, cache: false,

并正确发送文件