在symfony2中使用ajax上传图片

时间:2015-10-28 18:57:51

标签: php jquery ajax symfony

我想点击图片打开窗口选择新图片,然后更改屏幕,现在我想在银行中更改此图片,但这个待处理的错误:

  

捕获致命错误:参数1传递给   Delivve \ WebBundle \ Entity \ User :: setFile()必须是。的实例   Symfony \ Component \ HttpFoundation \ File \ UploadedFile,字符串给出,   呼唤   /home/delivve-webservice/src/Delivve/WebBundle/Controller/UserController.php

我不知道错误是否在我正在拍摄的路径图像中?

$("#bundle_user_file").change(function () {
    if (this.files && this.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('.active-img').attr('src', e.target.result);
            ajax_formData(e.target.result);
        };
        reader.readAsDataURL(this.files[0]);
    }
});

function ajax_formData(image) {
    var path = "{{ path("submit_image_user", {"userId" : owner.id}) }}";
    alert(image);
    $.post(path, {image: image}, function (data) {
        alert(data.message);
    }, "json");
}

public function submitImageAction(Request $request, $userId){
    $this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');

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

    $entity = $this->getUser();

    if ($entity->getId() != $userId) {
        $response = new JsonResponse(
            array(
                'message' => "Não tem permissão de alterar esses dados"
            ), 400);

        return $response;
    }

    if ($base64Content = $request->request->get('image')) {
        $filePath = tempnam(sys_get_temp_dir(), 'UploadedFile');
        $file = fopen($filePath, "w");
        stream_filter_append($file, 'convert.base64-decode');
        fwrite($file, $base64Content);
        $meta_data = stream_get_meta_data($file);
        $path = $meta_data['uri'];
        fclose($file);
        $entity->setFile($path);
        $entity->upload();
        $em->persist($entity);
        $em->flush();

        return new JsonResponse(array('message' => 'Success!'), 200);
    }

    $response = new JsonResponse(
        array(
            'message' => "imagem não encontrada"
        ), 400);

    return $response;
}

这是我班上的方法 user.php的

/**
     * @return string
     */
    public function getPictureUrl()
    {
        return $this->pictureUrl;
    }

    /**
     * @param string $pictureUrl
     */
    public function setPictureUrl($pictureUrl)
    {
        $this->pictureUrl = $pictureUrl;
    }

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * Set file.
     *
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
    }

    /**
     * Relative path.
     * Get web path to upload directory.
     *
     * @return string
     */
    public function getUploadPath()
    {
        return 'uploads/pictures';
    }

    /**
     * Absolute path.
     * Get absolute path to upload directory.
     *
     * @return string
     */
    protected function getUploadAbsolutePath()
    {
        return __DIR__ . '/../../../../web/' . $this->getUploadPath();
    }

    /**
     * Relative path.
     * Get web path to a cover.
     *
     * @return null|string
     */
    public function getPictureWeb()
    {
        return null === $this->getPictureUrl()
            ? null
            : $this->getUploadPath() . '/' . $this->getPictureUrl();
    }

    /**
     * Get path on disk to a cover.
     *
     * @return null|string
     *   Absolute path.
     */
    public function getPictureAbsolute()
    {
        return null === $this->getPictureUrl()
            ? null
            : $this->getUploadAbsolutePath() . '/' . $this->getPictureUrl();
    }

    /**
     * Upload a cover file.
     */
    public function upload()
    {
        if (null === $this->getFile()) {
            return;
        }
        $filename = $this->getFile()->getClientOriginalName();
        $this->getFile()->move($this->getUploadAbsolutePath(), $filename);
        $this->setPictureUrl($filename);
        $this->setFile();
    }

我得到的文件来自类型base64,我必须把它变成一个上传文件

$file = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAA..."

如果有人能帮助我做这个异步文件的提交,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

public function submitImageAction(Request $request, $userId)
{
    $this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');

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

    $entity = $this->getUser();

    if ($entity->getId() != $userId) {
        $response = new JsonResponse(
            array(
                'message' => "Não tem permissão de alterar esses dados"
            ), 400);

        return $response;
    }

    if ($base64Content = $request->request->get('image')) {
        $dat = preg_split("/,/", $base64Content);

        if (($fileData = base64_decode($dat[1])) === false) {
            $response = new JsonResponse(
                array(
                    'message' => "Base64 decoding error."
                ), 400);

            return $response;
        }
        $fileName = $entity->getUploadPath() . "/" . uniqid() . ".jpeg";
        if (file_put_contents($fileName, $fileData)) {
            $entity->setPictureUrl($fileName);
            $em->persist($entity);
            $em->flush();

            return new JsonResponse(array('message' => 'Success!'), 200);
        }
    }

    $response = new JsonResponse(
        array(
            'message' => "imagem não encontrada"
        ), 400);

    return $response;
}

驱动程序中的错误只需要像发送用户

的路径一样