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条回答 默认 最新

  • douliaodan2738 2016-04-23 12:22
    关注

    Run in browser console.log(JSONimage) just before $.ajax. You are not sending file but object with image properties.

    Try using https://github.com/1up-lab/OneupUploaderBundle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组