Implementing Ajax image upload functionality in Symfony2 framework

I am trying to implement a functionality where clicking on an image opens a window to select a new image and update the screen. However, when attempting to change the picture in the database, I encountered the following 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

Is the error possibly related to the path of the image I am retrieving?

$("#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 some methods from my `user.php` class:

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

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

    // Other methods omitted for brevity...

    /**
     * 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 receive is in base64 format and needs to be converted into an UploadedFile.

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

I would appreciate assistance with implementing asynchronous file submission. Thank you!

Answer №1

function processImageData(Request $request, $userID)
{
    $this->denyAccessUnlessAuthorized('ROLE_USER', null, 'You do not have permission to access this page!');

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

    $entity = $this->getUserInfo();

    if ($entity->getId() != $userID) {
        $errorResponse = new JsonResponse(
            array(
                'message' => "You do not have permission to alter this data."
            ), 400);

        return $errorResponse;
    }

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

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

            return $responseError;
        }
        
        $newFileName = $entity->getImagePath() . "/" . uniqid() . ".jpeg";
        
        if (file_put_contents($newFileName, $decodedImage)) {
            $entity->setImageUrl($newFileName);
            $manager->persist($entity);
            $manager->flush();

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

    $notFoundResponse = new JsonResponse(
        array(
            'message' => "Image not found"
        ), 400);

    return $notFoundResponse;
}

The issue was with the driver needing to correctly handle sending the path to the User.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Symfony 4.4.17 logout issue on live server

Having an unusual issue with Symfony 4.4.17 on the production server, as it works fine locally. Running PHP 7.3.21 on the development environment and PHP 7.3.23 on the production environment. The logout feature is not functioning properly without any err ...

In PHP, the last character of a string is moved to a new line

One problem I'm encountering is when I add the last character to a string like this: $cookie = $cookie . ";"; The ';' ends up on a new line when I save it to a .txt file. If you have any tips on how to keep the last character attached to ...

Steps for modifying the documents on an osCmax website

I had a developer set up my website in osCmax a while ago, and now I want to update the design of some pages using HTML and CSS on my own. While I am comfortable with HTML and CSS, I have very limited knowledge of PHP. This is my first attempt at working o ...

Populating a dropdown box in MySQL database using PHP and implementing a search function

Hi there, I have a question about creating a search feature on a webpage using a textbox and a dropdown box. The table I am working with has the following fields: Occupation field) and allows users to input additional search criteria in a textbox, return ...

selecting options from a drop-down menu within a table's row

I am currently working on a project where I need to populate a table in PHP by reading data from a file and parsing it line by line. One of the fields in the table needs to display a drop-down select list with predefined values, not generated dynamically. ...

The absence of the Ajax Template in Rails 4 is causing a setback

While practicing, I attempted to add a basic message form with an Ajax call. However, I encountered an error indicating that a template is missing. The error seems to be related to the Devise gem and reads as follows: Missing template messages/create, app ...

What is the best method to compare dates in JavaScript/JQuery to determine if one comes before the other?

I am completely new to JavaScript development and I need to accomplish the task below: I have 2 input tags containing 2 strings representing dates in the format 01/12/2014 (DAY/MONTH/YEAR). These input tags are used to search for objects with a date field ...

Best event for Angular directive to bind on image onload

I'm currently working on incorporating this particular jQuery plugin into my Ionic application. Although I have a good grasp of creating an Angular directive to encapsulate the plugin, I am encountering difficulties in successfully implementing it. B ...

Issues detected with the callback function of jQuery validation engine

I am currently utilizing the jQuery ValidationEngine plugin to validate a form. The validation itself is working fine, however upon completion, instead of redirecting to the previous page as expected, a JSON string is displayed on the screen. Below is the ...

Creating a multi-dimensional array structure from a database result set - what's the best approach?

My Json array of events is as follows: [ { "id": "4", "event_name": "Harliquins 7s", "event_description": "Ruggby game", "event_date": null, "event_venue": "UFA grounds", "event_company": "Harliquins", ...

What is the best way to manage a session using JavaScript?

Currently developing a website that initially hides all elements except for the password box upon loading. Once the user enters the correct password, all webpage elements are revealed. Seeking a solution to keep the elements visible on reload by utilizing ...

jQuery Autocomplete - Showing array of options upon selecting input field in Internet Explorer

After encountering an issue with the autocomplete feature in a web application, I posted a question on Stack Overflow. The provided answer solved the problem in Chrome, but unfortunately, it did not work in Internet Explorer 8 or 9, and possibly earlier ve ...

Angular 2/Typescript experiencing a glitch with Jquery carousel functionality

After properly installing and importing jquery in my project, I encountered a specific issue. Within my application code, there is a line that reads as follows: $('#myCarousel').carousel("next"); Upon running npm start, an error is thrown: ...

Instructions on creating a PHP file key that automatically expires after 10 days, preventing other users from accessing the API once the key has expired

My goal is to create a key that remains valid for 10 days from the date of generation. This key should allow anyone to access an API for a period of 10 days. I specifically want to implement this functionality using PHP only, without relying on sessions or ...

Looping through a JSON array

Currently, I am working with asp.net in Visual Studio and using jQuery to call a web method. In asp.net, I am generating a dynamic datatable and then returning it by using JsonConvert.SerializeObject(dt). $.ajax({ type: 'POST', url: &apo ...

The switch switches on yet another switch

Greetings everyone, Currently, I am in the midst of my exam project and creating a mobile menu. The functionality is there, but unfortunately, when closing the menu, it also triggers the search toggle which displays an unwanted div, becoming quite botherso ...

Broaden the reach of the ajax .done function to encompass the surrounding function

It seems like my previous attempts to find a solution for the function below were unsuccessful: function countNoFilters(keyword){ keyword = typeof keyword !== 'undefined' ? keyword : "keyword="+$("#keyword-hidden").val(); var getR ...

I seem to be having some issues with the functionality of .not() and it's

I am working on creating a menu that remains open for a set amount of time and then fades out if neither the parent nor the menu is hovered over. The goal is to have all other menus close when hovering over a new parent in the menu, but the current code k ...

php list may or may not display indents or hyperlinks

I have implemented the following code to display a list of all files in a directory: <?php if ($handle = opendir('CD300/')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".."){ ...

Trigger an event on an element upon first click, with the condition that the event will only fire again if a different element is clicked

Imagine having 5 span elements, each with an event listener like ` $('.option1').on("click", function(){ option1() }) The event for option 1 is also the default event that occurs on page load. So if no other options are clicked, you won&apo ...