Symfony is unable to access uploaded files from an AngularJS interface

For the past 3 days, I've been grappling with uploading files via AJAX to my Symfony2 application using AngularJS.

I'm utilizing my Symfony app as an API to deliver data to my Angular front end. While I can successfully post text and other data, I've hit a roadblock when it comes to posting files from the front end to the back end.

With the help of the chrome plugin DHC, I managed to post a picture and retrieve the object from the $request variable, but Angular seemed to be a dead end in this scenario.

I experimented with various solutions like dropzoneJS, ng-file-upload services, and more, but none seemed to do the trick. So, I reverted to using a basic hidden iframe, yet even that didn't work effectively. It appears that the request is being converted to a GET by the time it reaches the back end, despite being sent as a POST.

Feeling stuck and frustrated, I decided to start over with my PHP controller code.

Here's a glimpse of my current code:

Angular view :

<div class="uploadTest">
    <form id="file_upload_form" method="post" enctype="multipart/form-data" action="/submission" ng-submit="submit()">
        <input name="file" id="file" size="27" type="file">
        <input type="submit" name="action" value="Upload">
        <iframe id="upload_target" name="upload_target" src="" style="width:580px;height:580px;border:2px solid red;"></iframe>
    </form>
</div>

Angular controller :

angular.module('mondialatorApp').controller('UploadCtrl', ['$scope', function ($scope){
    $scope.submit = function(){
        document.getElementById('file_upload_form').target = 'upload_target';
    }
}]);

My PHP controller (which was empty due to lack of progress):

class SubmissionController extends Controller{
    public function addAction(Request $request){
        return new Response('done');
    }
}

My routing file :

mondialator_submission_add:
    path: submission/
    defaults: {_controller: MDMondialatorBundle:Submission:add}

Lastly, examining the content of $request variable:

object(Symfony\Component\HttpFoundation\Request)[7]
   // Content of $request goes here

I've scoured through numerous forums and websites without finding a solution. The issue seems elusive, and I'm at a loss for what to try next. In the words of Leia, "You are my only hope."

Answer №1

If you're looking to implement HTML 5, here's a way to do it:

Using HTML:

<div ng-controller="UploadCtrl">
  <form id="file_upload_form">
    <input type="file" id="file" name="file">
    <button ng-click="submit()">Submit</button>
  </form>
</div>

And in Javascript:

angular.module('uniqueApp', []).controller('UploadCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.submit = function () {
        var file = document.getElementById('file').files[0],
        reader = new FileReader();
        reader.onloadend = function (event) {
            var data = event.target.result; // Contains uploaded file content
            var request = {
                method: 'POST',
                url: '//example.com/your-endpoint',
                headers: {
                    'Content-Type': 'some-type-spec'
                },
                data: data
            };
            $http(request).then(function (response) {
                // handle success
            }, function (response) {
                // handle error
            });
        }
        reader.readAsBinaryString(file);
    }
}]);

Don't forget to specify your Symphony app's API endpoint where you want to post data in the req's url key.

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

Interactions within nested controllers

As a newcomer to Angular, I have been searching for a suitable solution to the following issue but have not found one that meets my needs. I have a very simple modal dialog controlled by ModalDialogCtrl which contains an edited object, such as Rabbit or Do ...

Ensure that a group of checkboxes is mandatory

I currently have a series of checkboxes set up like so: <label>What is your preferred movie genre?</label> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="genre1" name="genre" ...

"Encountering an issue with ASP.NET MVC and Angular when making an AJAX call with multiple parameters, the HttpPostedFileBase

When sending an object and a file from my Angular service, the following code snippet is executed: $scope.addProject = function () { { var project = {}; project["Id"] = $scope.Id; project["ProjectCode"] = $scop ...

What could be causing the issue with my Mongoose One-To-Many Relationships not linking correctly?

Can anyone shed light on why the connection between "users" and "posts" (where users can have multiple posts) is failing to work properly? Despite setting up my mongoose associations correctly, when a new post is made, it doesn't get assigned to a use ...

AngularJS extension known as 'ngclipboard'

I've been attempting to utilize a plugin called ngclipboard in Angular, but something seems amiss as it's not functioning as expected. There are no error messages, however, the text from the input box is not being copied to the clipboard. To see ...

Accordion in Bootstrap 5.3 behaving independently of data-bs-parent

I am currently working on designing an accordion feature where the headers are displayed in a column on the left side, and when expanded, the content appears in a column on the right side. Everything is working perfectly except for the fact that I have t ...

What is the best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class. interface IQuiz { quizProg: TypeQuizProg; qidx: number; state: IStateCtx; actions: IActionsCtx; } @observer class Comp extends Rea ...

Another option instead of using useCallback

Forgive me if this is a novice inquiry, but I am still learning JavaScript and React. I recently discovered the necessity of utilizing useCallback to wrap callback functions in order to prevent them from being recreated constantly when used within a fun ...

When combining Socket.io 1.0 with express 4.2, the outcome is a lack of socket connection

According to the title, I am attempting to integrate socket.io 1.0.4 with express 4.2, but all requests with "/?EIO" are resulting in a 404 error. Below are my file configurations: ./bin/www : #!/usr/bin/env node var debug = require('debug')(& ...

The frequency of the geolocation watchPosition in Cordova exceeds the set options

In my ionic/angularjs application, I am utilizing the geolocation plugin from this link: https://github.com/apache/cordova-plugin-geolocation Following the documentation, I have set up the watch configuration as shown below: var watchOptions = { freq ...

Locating the Active Object's Coordinates in fabric.js

When using fabric js, I have successfully drawn various shapes like circles and rectangles. However, I encountered an issue while trying to obtain the coordinates of the rectangle using the fabric.rect() method. canvas.getActiveObject().get('points& ...

Tips for displaying an element for each item chosen in a multi-select box

I currently have a situation where I am rendering for every selected element within my multiselect angular material selectbox. The rendering process functions correctly when I select an element, but the issue arises when I try to deselect one - it just ke ...

Tutorial: Using Laravel 5.6 to transfer selected value from Dropdown menu to PHP variable using Ajax on a single page

In my current project, I am utilizing Laravel 5.6 alongside PHP 7.1.9. On a specific page (pages/cardview.blade.php), I have a dropdown box with different options and PHP conditions to check the selected value from this dropdown. Based on the selection, ce ...

Retrieve information using AngularJS only when it is not yet defined

Currently, I am using $http in a controller to retrieve data and display it to the user. However, once the data is fetched for the first time, I do not want to fetch it again when moving between different tabs or controllers. My expertise lies in web dev ...

Exploring the Angular framework: Combining form requirements and controllers in directives' link functions

In my coding journey, I have developed a powerful directive known as formNavHandler. This directive plays a crucial role in handling dirty checking and smooth navigation between different pages. The functionality of formNavHandler heavily relies on the exp ...

Seeking assistance with creating a Django + Ajax feature for a like button

I am a beginner in the coding world and have recently added the like button feature to my project using the resources from the online book - Tango with Django. However, I am facing a challenge where I need to keep track of which users have liked what conte ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

Removing filters dynamically from ng-repeat in Angular

I am currently using ng-repeat to display a list of staff members: <div ng-repeat="user in staff | profAndDr"> There is also a custom filter called 'profAndDr' that only shows people with the titles "Dr." and "Prof.": app.filter('pr ...

Safeguarding Information about Objects

Currently, I am developing a program that allows users to retain search terms from one session to another. When a user preserves a search term, the corresponding data is also saved. At the start of each session, any outdated data is discarded if it does no ...

Manipulate JSON data structure with JavaScript

The initial JSON data: { "data": { "count_at_hub": [ { "hub": "A", "date": "", "size": "1", "count": 141 }, { "hub": "A", "date": "", "size": " ...