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

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效