gpt4 book ai didi

php - Symfony2 : Uploads a file using Ajax and jQuery

转载 作者:可可西里 更新时间:2023-11-01 12:47:30 25 4
gpt4 key购买 nike

我有一个 Symfony2 应用程序,它的表单中有一个文件类型字段。我需要在那里上传一张学生的照片,所以我帮助了这个文档:How to Upload Files

这是我的代码:

Controller :

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 Controller 中使用。

我看过一些FormData(),但不知道怎么用。

你能帮帮我吗?

最佳答案

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

  • data: new FormData($(this)[0]) 而不是 data: $ (this).serialize()

  • 添加ajax请求:

    processData: false, contentType: false, 缓存:false,

文件已正确发送

关于php - Symfony2 : Uploads a file using Ajax and jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com