The AngularJS "multipart form" file upload is encountering an issue where undefined values are being sent to the server. As a result, the file cannot be

Here is the HTML code I am working with:

    <form >
        <input type="file" file-model="myFile"/>
       <button ng-click="uploadFile()">upload me</button>
   </form>

Inside my controller, I have the following function:

$scope.uploadFile = function() {
        var file = $scope.myFile; 
        var fd = new FormData();
        fd.append('file', file);
        $http.post("url", fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined},
                transformResponse: [function (data) {
                    return data;
                }]
            }).then(function (result) {
            console.log(result.data);
        })
    }

The directives I'm using are as follows:

.directive('fileModel', ['$parse', function ($parse) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;

                element.bind('change', function(){
                    scope.$apply(function(){
                        modelSetter(scope, element[0].files[0]);
                    });
                });
            }
        };
    }]);

I've noticed that I'm getting an undefined value for the file. Is there something wrong in my code?

Upon inspecting the browser's developer tools, it appears that I am passing undefined to the server. Here is a screenshot for reference:https://i.sstatic.net/JhstR.jpg

Answer №1

The issue stemmed from a non-binding problem with files, which Angular currently does not support. Fortunately, I was able to resolve it using the solution found in this helpful thread: AngularJs: How to check for changes in file input fields?

Answer №2

This method successfully resolved my issue:

<div>
    <input id="imageList" name="imageList" type="file" file-model="myFile">
</div>

I also included a JSON object to accompany the form submission:

$scope.saveForm = function () {
      var formData = new FormData();
      var file = $scope.myFile;
      formData.append("file", file);
      var req = {
        url: '/upload',
        method: 'POST',
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function (data, headersGetterFunction) {
          return data;
        }
      };

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 URL Errors with Spring REST

Currently, I am working on a project that involves using Spring REST web services. One of the key requirements is to display meaningful error messages gracefully when an exception or error occurs during the execution of the application. To achieve this, I ...

Retrieving the parent value in React-select grouped options

When using react-select with grouped options, the structure is as follows: { label: PARENT_NAME, value: PARENT_ID, options: [ { label: CHILD_NAME, value: CHILD_ID, } ] } An array of these options is passed to the component lik ...

Retrieve information from XML using jQuery

<?xml version="1.0" encoding="UTF-8"?> <slider> <csliderData1> <title>Kung Fu Panda</title> <content>In the Valley of Peace, Po the Panda finds himself chosen as the Dragon Warrior despite</content ...

"Implementation of clearInterval function may not always result in clearing the interval

The scrolling process within the div element flows smoothly in both directions, however, it seems to encounter an issue when executing the scrollBack() function. Despite including a clearInterval() statement at the intended point, the interval does not a ...

Angular JS Visibility Toggling with Ng-Show and Ng-Hide

Working on an angular service for a login form, I've successfully implemented authentication using a factory with an http injector to handle HTTP credentials. However, I'm facing an issue in displaying an error message when incorrect credentials ...

You cannot reassign NodeJS global variables

Currently, I am in the process of writing unit tests for code that utilizes a JavaScript library. This particular library sets a global variable if it does not already exist using the following pattern: var GLOBAL_VAR = GLOBAL_VAR || {} While this method ...

When the textbox fails validation, it should display an error message within the same textbox and prevent the user from proceeding to another textbox

Here is a JavaScript function and a textbox in the code snippet below. The validations work perfectly. The goal is to clear the textbox value and keep the cursor in the same textbox if the validation fails, without moving to other controls. JS: function ...

Creating synchronous behavior using promises in Javascript

Currently, I am working with Ionic2/Typescript and facing an issue regarding synchronization of two Promises. I need both Promises to complete before proceeding further in a synchronous manner. To achieve this, I have placed the calls to these functions in ...

Guide on Implementing jQuery Plugin with Vue, Webpack, and Typescript

I am currently exploring the integration of the jQuery Plugin Chosen into my vue.js/Webpack project with TypeScript. After some research, I discovered that it is recommended to encapsulate the plugin within a custom Vue component. To kick things off, I m ...

Step-by-step guide on updating a database using AJAX post serialization in PHP, jQuery, and JavaScript

I am facing an issue with updating my rooms table using the update query from serialize. Instead of saving all the data, it only updates the first row in the table. Here is my room list in the rooms table of my database: 1 Room1 Regular 2 Room2 ...

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

What is the best way to navigate to a different page when scrolling in React Router?

I am working on a design that includes a landing page with 100vh and 100vw dimensions. I want it to transition into another page as the user scrolls down. How can I achieve this using React hooks and React Router? Any guidance or suggestions would be high ...

Tips for creating a for loop in a .js script within MongoDB that allows for passing a variable containing the database name to a text file

In a .txt file, I have a list of database names as shown below: local test admin Is there a way to dynamically pass arguments instead of hardcoding them in .js scripts for mono go? db = db.getSiblingDB('test'); date = new Date() dat ...

Determine if a point within a shape on a map is contained within another shape using Leaf

I have extracted two sets of polygon coordinates from a leaflet geoJSON map. These are the parent and child coordinates: var parentCoordinates=[ [ 32.05898221582174, -28.31004731142091 ], [ 32.05898221582174, -2 ...

Toggle between two different global SCSS styles using a selector

I am in the process of upgrading my company's AngularJS project to Angular 8 using ngUpgrade. This has resulted in a hybrid application with components from both AngularJS and Angular. Additionally, I am utilizing an angular material template that inc ...

What is the reason for the excessive width of the final column in this table?

I am currently working with a dataset that I am displaying using the handsontable library in the form of a table. One issue I am facing is that the last column of my table appears too wide even though I did not specify any width for it. Below you can see t ...

Consolidating multiple inputs into a single saved value

How can I combine three input values into one input field using onchange event in JavaScript? <script type="text/javascript"> function updateInput($i){ $('updateval').val($i); } </script> <input type="text" onchange="updat ...

I need help in updating my user information using jQuery, JavaScript, AJAX, and the Node.js API

Working with a dynamic table that fetches JSON data from the API (/api/dashboard/v1) using the GET method. There is another API (/api/updateUser/v1:id) available for updating user information using the PUT method. A table has been created with an Edit op ...

Switching text without the need for a button click

Hello, I am a beginner in android studio development and could use some help. I have successfully created a textswitcher that changes text on button click, but I want to make it swipe to the next text when the user interacts with the screen instead of clic ...

Executing Multiple Test Suites with TestNG

Can multiple test suites be created and executed using TestNG? I am looking to link a suite with a specific build to maintain a consistent structure for each suite, with changing build numbers and tests. Below is an example of one suite I am currently us ...