douren2395
douren2395
2015-10-28 18:57

在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 dozoqn3347 6年前
    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

    点赞 评论 复制链接分享