doujianzhi3358
2016-04-23 07:27
浏览 49
已采纳

Symfony将json编码的文件对象添加到实体

I'm trying to pass a file object to PHP and persisting it to my database with an AJAX call the following way:

Js:

e.preventDefault();

    // get the file object from input
    var image = $('#profilePictureInput').prop('files')[0];

    // recreate file object
    var newImage  = {
        'lastModified'     : image.lastModified,
        'lastModifiedDate' : image.lastModifiedDate,
        'name'             : image.name,
        'size'             : image.size,
        'type'             : image.type
    };

    // convert to JSON to be able to send to controller
    var JSONimage = JSON.stringify(newImage);

    // update profilepicture
    $.ajax({
        type: 'POST',
        url: Routing.generate('uploadProfilePicture'),
        data: {
            'image' : JSONimage,
        }
    })
    .done(function (response) {
        console.log(response);
    });

My PHP controller:

$image = $this->get('request')->request->get('image');

    if ($image){
        // decode JSON object to php array
        json_decode($image);

        $em = $this->getDoctrine()->getManager();

        // insert new image object
        $image = new Image();
        $image->setFile($image);

        $em->persist($image);
        $em->flush($image);

        return new JsonResponse('success');
    }
    return new JsonResponse('false');

But when I run this script it returns a "500 internal server error"

My question here: I have an object inside my php, containing the image values as follows:

{"lastModified":1459104697000,"lastModifiedDate":"2016-03-27T18:51:37.000Z","name":"download (2).jpeg","size":5986,"type":"image/jpeg"}

How can I now convert this object in PHP to be accepted as a file inside my Entity?

Help would be much appreciated!! Thanks!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题