加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Symfony2:使用Ajax和jQuery上传文件

发布时间:2020-12-13 18:14:08 所属栏目:PHP教程 来源:网络整理
导读:我有一个Symfony2应用程序,其中包含一个文件类型字段的表单.我需要在那里上传一个学生的图像,所以我帮助了这个文档: How to Upload Files 这是我的代码: 控制器: public function createAction(Request $request){ if ($request-isXmlHttpRequest() !$req
我有一个Symfony2应用程序,其中包含一个文件类型字段的表单.我需要在那里上传一个学生的图像,所以我帮助了这个文档: 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 DoctrineORMMapping as ORM;
   use SymfonyComponentValidatorConstraints as Assert;

   //...
   /**
   * @var string
   *
   * @ORMColumn(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:

//...

$('.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(),但不知道它是如何使用的.

你可以帮帮我吗?

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

> data:new FormData($(this)[0])而不是数据:$(this).serialize()
>添加ajax请求:

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

并正确发送文件

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读