Having trouble sending files from AngularJS to ExpressJs

Currently utilizing the angular-file-upload packages for file uploads. When triggering item.upload(), it reports a successful upload, but the req.body appears to be empty. Assistance needed!

The following is the angular code snippet:

var uploader = $scope.uploader = $fileUploader.create({
        scope: $scope,                          // to automatically update the html. Default: $rootScope
    url: '/api/teams/upload',
    formData: [
        { key: 'value' }
    ],
    filters: [
        function (item) {                    // first user filter
            $scope.previewImage(item);
            return true;
        }
    ]
});

To kick off the upload process, refer to the following code:

uploader.bind('afteraddingfile', function (event, item) {
    // console.info(item.file);
    console.info('After adding a file', item);

    // console.log('item.upload();');
    item.upload();
});

Finally, here's the ExpressJS code snippet:

exports.upload = function(req, res) {
// console.log('req.headers');
// console.log(req.headers);

console.log('req.body');
console.log(req.body);

What could be the issue here?

Answer №1

To ensure your POST is properly encoded, be sure to include enctype="multipart/form-data"....

In Express 4, it is necessary to configure the body parser in your server:

var bodyParser     = require('dy-parser');
//...

var app            = express();
//...
app.use(bodyParser());  // retrieve data from html in POST requests

var busboy = require('connect-busboy');    
app.use(busboy());

In earlier versions of Express, simply adding the framework's body parser was sufficient and files would be stored at the specified location:

     app.use(express.bodyParser({limit: '10mb', uploadDir: __dirname + '/public/uploads' }));               // retrieve data from html in POST requests

With support for connect removed in version 4, custom support for multipart/form data needs to be added in order to parse multi-part POSTs, requiring a setup similar to:

var fs = require('fs');
var busboy = require('connect-busboy');

//...
app.use(busboy()); 
//...
app.post('/api/teams/upload', function(req, res) {
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file, filename) {
        console.log("Uploading: " + filename); 
        fstream = fs.createWriteStream(__dirname + '/files/' + filename);
        file.pipe(fstream);
        fstream.on('close', function () {
            res.redirect('back');
        });
    });
});

For the client side operation, use $upload.upload to initiate the upload process.

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

Is the function failing to detect the updated variable because it is not declared as a global variable?

I have created a quiz with 7 select boxes and a submit button, aiming to display a warning error if the select boxes are not changed or show the score if they are changed. I initialized a variable called 'changed' as false. When a select box is ...

Tips for assigning an AngularJS data-bound value to the href attribute of an anchor tag

I need to include multiple email ids separated by commas from an angularjs binded value in the mailto field of an anchor tag. The team.emails variable can contain either a single email id or multiple email ids separated by commas. <tr ng-repeat="team ...

In Node.js, use the `[]` operator to select elements from an array of strings without including

In my situation, I am working with an array of strings which can sometimes be an array containing only one string. The issue is that when this happens, using array[0] to retrieve the value does not return the entire string but rather just the first charact ...

Injecting AngularJS service into a karma-mocha test: Step-by-step guide

I have developed a Karma-Mocha test that involves injecting an AngularJS service. Service Code: (function() { 'use strict'; angular.module('portal').service( 'AmountFormatService', functio ...

Navigating the Angular Mindset

Currently, I am tackling a project consisting of over 1500 HTML pages. The initial implementation of this project utilized jQuery and JS code. However, my task now is to modernize this Single Page Application (SPA) by incorporating AngularJS. While I have ...

Sending image URLs from Postgres to the front-end using Node and React

One of the functions in my app allows me to submit a form with images, which are then stored in a file using Multer and their URL is uploaded to my Postgres database. However, when I retrieve the file on the front end, I only get the image filename without ...

Display an image in an Angular application using a secure URL

I am trying to return an image using a blob request in Angular and display it in the HTML. I have implemented the following code: <img [src]="ImageUrl"/> This is the TypeScript code I am using: private src$ = new BehaviorSubject(this.Url); data ...

Refreshing Form in Angular 2

When I remove a form control from my form, it causes the form to always be invalid. However, if I delete a character from another input field and then add the same character back in (to trigger a change event), the form becomes valid as expected. Is ther ...

Generating Angular select options dynamically using ng-repeat

I've been struggling for several days now with ngOptions and ngRepeat. I am trying to create a select option for a people control. The REST service is returning an array as shown below. Despite trying various solutions from Stack Overflow and the Angu ...

Icon-enhanced Bootstrap dropdown selection

I have a unique select dropdown using Bootstrap where I want to display icons like the example below: https://i.sstatic.net/dZmTS.png <!DOCTYPE html> <html> <head> <script src="/scripts/snippet-javascript-console.min.js?v=1"& ...

Tips on modifying event object properties in an array based on subsequent array input during calendar creation on a webpage

1. I'm faced with the challenge of developing an event calendar that is compatible with all web browsers. For instance: 2. If I schedule an event from 9:30 to 10:30 am, it should occupy 100% width on the calendar. 3. Then, when I add another event f ...

What is the best method for extracting a value from a JSON file within an array using electron and node.js?

Hey there, I'm currently working with a JSON file that contains an array of value sets. I'm trying to figure out how to extract the first value from the initial set, specifically the value 3 under the key "pink". This is all being done in Node.js ...

Understanding JavaScript Prototypal Inheritance within ES5 Classes

I've been working on creating an XMLHttpRequest interceptor for Angular, encountering a roadblock when trying to intercept a third-party library that uses the XMLHttpRequest API. Although the solution below is functional, I've run into issues wit ...

Tips for choosing elements based on a specific attribute (such as fill color) in D3.js using the SelectAll method

I have various sets of circles on a map - 10 red circles, 10 blue circles, and 10 green circles. Is there a way to use d3 selectAll or select to specifically choose only the red circles? Are there any alternative methods for achieving this? The color of ...

Mapping choices array in ReactJS using the id as a key reference

Looking for assistance with JavaScript as I am relatively new to it. I have a page displaying scheduled exams, and clicking on "Learn more" opens a modal where you can edit exam details. Currently, the modal displays selected equipment and allows changing ...

Establishing a session using express node.js and mongoose

Currently, I am working on an application using Node.js, Express, and MongoDB (mongoose). I am facing a challenge in establishing the database connection in a separate file from server.js, especially with connect-mongo. Initially, my server.js looked like ...

How to create a donut chart in Highcharts without an inner pie section?

I've been scouring the internet in search of a solution to create a basic donut chart using the Highcharts library. Most examples I come across show donut charts with both an inner pie and outer donut (see here). Is there a way to remove the inner pi ...

Retrieve image details and display them in the console when the page is resized

Query: How can I retrieve and monitor the src, width, and height of all images on a webpage and display this information in the console whenever the page's size changes? Sample Code Snippet: var images = document.getElementsByTagName('img' ...

Creating a fixed sidebar that remains visible while scrolling in Next.js

Currently, I am faced with the challenge of implementing two components - a feed and a sidebar. The sidebar contains more content than it can display at once, so I want it to be able to overflow. My goal is to have the sidebar scroll along with the content ...

ngTransclude not encompassing any content whatsoever

I am facing an issue with a custom Angular directive that is used in several of my AngularJS views. The directive is set to transclude, but the wrapped content is not appearing. app.directive('card', [function() { return { restrict: "E", ...