Guide to using AngularJS to upload FormData object

I recently started using angular-js and encountered a problem when trying to submit multipart/form-data with an image. The $http.post() method only supports json format, so I needed to convert the formdata object to json format.

$scope.SubmitForm=function()
{
    url = siteurl + '/admin/' + $scope.module + '/add';

    var form=document.getElementById("addForm");
    var formData=new FormData(form);

    $http({
        url     :   url,
        method  :   "POST",
        data    :   formData,
    })
    .then(function(responseText) {                
        alert(JSON.stringify(responseText));

    //process data
    },function(){
        alert("hello from error");
    });

} 

Unfortunately, this approach did not work for me. I then tried converting the data to json format and it worked fine.

formData={
    "first_name" :  $('#first_name').val(),
    "last_name"  :  $('#last_name'),
    //....
};

However, I was unsure of how to append my image file to this format. Any suggestions on how to achieve this?

Is there a specific function that can help in converting formdata object to json format?

Answer №1

After incorporating the following two lines of code in the $http configuration section, the issue was resolved (thanks to everyone who helped)-

      $http({
            url     :   url,
            method  :   "POST",
            data    :   formData,
            transformRequest: angular.identity, // refer to AngularJS documentation
            headers : {'Content-Type':undefined}// changing content type to undefined alters the default content type of AngularJS
        }).then(function(responseText){
            
            alert(JSON.stringify(responseText));
            ///$scope.tablerows=$scope.totaltablerows;
            ///$scope.searchFunction();
        },function(){
            alert("hello from error");
        });

This simple solution worked for me.

Answer №2

When dealing with forms in Angular, it's highly recommended to utilize the ng-model directive. This creates a scope variable within your controller that allows for two-way data binding. If you don't have a form available, you can set it up like this (this is just a simplified example and not tested):

<form name="myForm" ng-submit="SubmitForm()">
    Name: <input ng-model="fields.name">
    Address: <input ng-model="fields.address">
    ....
</form>

In your JavaScript controller:

 $scope.submitForm = function(){    
        var data = $scope.fields,
            url = '/admin/' + $scope.module + '/add'; // Assuming $scope.module is accessible from other parts of the code  

        $http.post(url, data).then(function(resp){
        // Handle response...

        });        
    }

For more information, check out the documentation here: https://docs.angularjs.org/api/ng/directive/ngModel. You can also find examples on W3schools: http://www.w3schools.com/angular/angular_forms.asp

Answer №3

To achieve the desired outcome, follow this structure:

  let form = document.getElementById('addForm');
  let formData = new FormData(form);
  let fileToUpload = this.files[0];    
  formData.append("uploadedFile", fileToUpload);
  // Additional parameters can be added like this
  formData.append("first_name", $('#first_name').val());
  formData.append("last_name", $('#last_name').val());

Check out this GitHub example for reference.

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

Tips for enhancing the width of the extrude shape in the x and z axes using Three.js

After creating a shape using extrude geometry, I found that I needed to increase the thickness along the x and z axes. Although I used bevelThickness to increase the thickness along the y axis, I still need to adjust it further. For reference, please see ...

Why does JQuery ajax always fail to succeed? Where could the error be?

I am attempting to create an ajax call to a php server that utilizes Wordpress. I have set up a rewrite rule to handle the redirection of ajax calls: function Ajax_rules_setup(){ add_rewrite_rule( 'ajax/([^/]*)', ...

Waiting for the UI data filter to be available in Selenium

Within an application, numerous fields are present with individual filters (text boxes). As soon as a user enters a value in any of the filters, the UI data (in a table) immediately refreshes. I prefer to wait for the UI data to load before applying anoth ...

The oninput event does not trigger if the text field value is transferred from a different form

Event Handling: The oninput event functions perfectly when I input a mobile number into the small text field in my form. It displays a message indicating that the number already exists and disables the submit button accordingly. However, it fails to valida ...

I am looking to modify the dimensions of the grouped GridHelper through the graphical user interface

I'm having trouble resizing the grid using the GUI interface. How can I adjust its size? Here are the steps I followed to create it. let scene = new THREE.Scene(); scene.background = new THREE.Color(0x222222); let group = new THREE.Group(); scene.add ...

What are the differences between using .val() and .innerHTML?

When working with JQuery and trying to access elements, I have noticed that the method for retrieving content differs depending on the element type. For example, if I have a form with a textarea and want to get the text inside of it, I would use $("textare ...

Unable to access GLB model after building it in Three.js

Using GLTFLoader, I successfully imported a model that works flawlessly with npm run dev. However, when I attempt to build it using npx vite build, the model file seems inaccessible. The file is located at /public/models/miku_pde.glb. When running npm run ...

When encountering an issue while invoking a function in Vue.js, an internal error may occur, as evidenced by the message: "new Http

Currently, I am in the process of developing an application and encountering an issue where I am unable to comprehend a cryptic error message that keeps popping up. If you'd like to see the error itself, you can check it out here. Below is my form.vu ...

The Bootstrap4 nav-tabs are mistakenly causing the entire page to change instead of just the tab content

After encountering an issue on my Angular site while trying to incorporate a bootstrap nav-tab element, I decided to refer to some example code from the official Bootstrap documentation here. The problem arose when clicking on the tabs of my page resulted ...

JavaScript myfunction() onclick event not functioning correctly anymore

I have experience with this method in the past, but I am encountering issues when trying to implement it on a new website. The JavaScript button I used before is still functional on the old site, so I suspect there may be an error in my code even though ...

Using JSON in Highcharts: Customizing Border and Label Colors

Currently using Highcharts in JSON format with the following syntax: var neutral_color = '#c4c4c4', medium_grey = '#929292'; lineChartJSON['chart']['plotBorderColor'] = medium_grey; lineChartJSON['chart&ap ...

The response from the $http.get request indicates an HTTP status code of

I am currently experimenting with angularJS to interface with an API I developed. The root route of the API is set up to display information about the API in JSON format: { "Company": "Test Company", "Version": "0.1" } When I use jquery's $. ...

Is it true that Vue 3 + Inertia automatically removes event listeners upon component unmounting?

There is an event listener set up within the script setup block: <script setup> import {ref} from 'vue' const elementRef = ref(null) window.addEventListener('click', (event) => { if (!elementRef.value.contains(event.t ...

Updating binary files using Node.js

I am currently working on handling binary files in Node.js. My goal is to receive a binary file from the client, open it, convert it to hexadecimal, make some modifications, and then send back the updated binary file to the client. app.use('/read-bin ...

Is there a way to prevent text from overlapping a Material UI React Textfield when it is scrolled up and set to position sticky?

Scenario: In my chat application, I have the chat displayed in the middle of the screen with a sticky textfield at the bottom. My goal is to ensure that when users scroll through the chat messages, the textfield remains at the bottom but appears on top of ...

Transforming the API response

After making an Ajax call, the response received is: console.log(data); {"valid":true,"when":"Today"} Attempting to read the response like this: var res = data.valid; console.log(res); results in 'undefined' being displayed. To address this i ...

The second occurrence of a jQuery event

When a user left-clicks on the menu, it should load a view in a draggable box. However, the functionality is not working as expected. Sometimes you need to click twice - the first time the box appears but is not draggable, and the second time a new box app ...

Developing a component instead of a clicked event

My goal with Angular is to create a functionality similar to Google Maps. I have a background image/map, and I want to replace the map with an object/component where the user clicks with the mouse. Currently, I am able to obtain the x/y values. However, I ...

Synchronize two div elements with JavaScript

The demonstration features two parent divs, each containing a child div! The first parent div's child div is draggable and resizable using JQueryUI. There are events for both dragEnd and resizeEnd associated with this div. The goal is to synchronize ...

The CubeCamera function is encountering an issue where it is unable to access the 'up' property due to it being undefined

After a long time, I revisited my three.js project and was reminded of the days when I used to type out the full name PlaneBufferGeometry. The project features several vehicles that are supposed to reflect their environment (and each other) through the use ...