douren2395 2015-10-28 18:57
浏览 58
已采纳

在symfony2中使用ajax上传图像

I want to click on an image opens the window for selecting a new image, and change the screen, now I want to change this picture in the bank, but this pending on an error:

Catchable Fatal Error: Argument 1 passed to Delivve\WebBundle\Entity\User::setFile() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, string given, called in /home/delivve-webservice/src/Delivve/WebBundle/Controller/UserController.php

I do not know whether the error is in the path image that I'm taking?

$("#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;
}

these are the methods in my class 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();
    }

the file I get comes from the type base64, I have to turn it into a uploadfile

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

I would greatly appreciate it if someone could help me to do this submition of asynchronous file.

  • 写回答

1条回答 默认 最新

  • dozoqn3347 2015-12-08 19:04
    关注
    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;
    }
    

    the error was in the driver only need to hit like sending the path to the User

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

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系