Retrieving input data when utilizing ng-file-upload

I need help with uploading images and their titles using ng-file-upload in the MEAN stack. I am able to save the image successfully, however, I'm facing difficulty in retrieving the data sent along with it.

Controller:

module.exports = function ($scope, Upload) {
    let vm = this;

    vm.uploadImage = function () {
        if (vm.file) {
            vm.file.upload = Upload.upload({
                url: '/uploads/gallery',
                method: 'POST',
                data: { title: vm.title },
                file: vm.file
            });

            vm.file.upload.then(function (response) {
                $timeout(function () {
                    vm.file.result = response.data;
                });
            }, function (response) {
                if (response.status > 0) { }
                vm.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                vm.file.progress = Math.min(100, parseInt(100.0 *
                    evt.loaded / evt.total));
            });
        }
    }

    vm.browseImage = function (file, errFiles) {
        vm.file = file;
        vm.errFile = errFiles && errFiles[0];
    }
}

Route:

router.post('/gallery', (req, res) => {
    //multers disk storage settings
    let folder = './public/assets/images/gallery/';
    let filename = '';

    let imageLocation = '';
    let thumbLocation = '';

    let response = '';

    //console.log(req.form);------throws undefined
    //console.log(req.body);------throws undefined

    let storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, folder)
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            filename = file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1];
            imageLocation = folder + filename;
            thumbLocation = folder + 'thumb' + filename;
            cb(null, filename)
        }
    });

    //multer settings

    let upload = multer({
        storage: storage
    }).single('file');

    upload(req, res, function (err) {
        if (err) {
            res.json({ error_code: 1, err_desc: err });
            return;
        }
        else {
            response = { fileCreated: true };
        }
    })

});

module.exports = router;

How can I retrieve the string from my form in the route?

Answer №1

The upload.single(...) function serves as an express request handler, allowing for the use of multiple request handlers with a router matcher like the 'router.post' function in your code.

Instead of having just one request handler as shown below:

router.post('/gallery', (req, res) => {
...
...
}

You can modify your router to include multiple handlers like this:

router.post('/gallery', upload.single('file'), (req, res) => {
   ...
   ...
}

This approach enables the usage of multiple request handlers within your application.

To implement this, it is recommended to set up the multer instance outside the initial router matcher. Your updated file structure should resemble the following:

// Assuming these are already declared in your file
const express = require("express");
const multer = require("multer");
let router = express.Router();

// Multer's disk storage configurations
const folder = './public/assets/images/gallery/';
let filename = '';
let imageLocation = '';
let thumbLocation = '';

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, folder);
    },
    filename: function (req, file, cb) {
        var datetimestamp = Date.now();
        filename = file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1];
        imageLocation = folder + filename;
        thumbLocation = folder + 'thumb' + filename;
        cb(null, filename);
    }
});

// Multer settings
const upload = multer({
    storage: storage
});

router.post('/gallery', upload.single(), (req, res) => {
    console.log(res.json);
});

module.exports = router;

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

Create a function in JavaScript that is able to accept a variable number of objects as arguments

I have a good grasp of how to pass infinite parameters in a function in JavaScript. But what about accepting any number of objects as parameters in a function? This is my current implementation: function merge<T>(objA: T, objB: T){ return Object. ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

Exploring the iteration of JSON objects within an array using AngularJS

My auto search module has the following JSON structure. I need to iterate through an array of JSON objects and use keys and values as required. I have attempted the code below. However, with the provided JSON object, I am able to retrieve the key but not ...

What is the best way to transform the data received from this function into a DataTable that can be used with the Google Charts API?

Is there a way to easily convert the data returned by this function into a format that Google Charts API can read? public function ajax_get_dates(){ $data = ([['date1' => '04/08/2016'], ['date2' => '05/08/2016& ...

Sending back numerous information in the catch block

Recently, I was testing out the fetch API and encountered an issue with logging a fetch error. I tried catching the error and logging it within the catch block. Strangely, even when I added additional console.log statements in the catch block, they would ...

Creating a box that is connected by lines using JSON data requires several steps. You

I am attempting to dynamically draw a line using the provided JSON data. I have heard that this can be easily achieved with flexbox. Important: I would greatly appreciate a solution involving flexbox This is what I hope to achieve: https://i.stack.imgu ...

Ways to match a string against a numeric value

I have a span id with textContent which have their own time(hour/minutes) <div class="here"> <span class="time" >8 min</span> </div> <div class="here"> <span class="time" >22 min&l ...

An issue has occurred with NPM CI where the bindings are not available from watchpack-chokidar2:fsevents

After executing npm ci on GitHub Actions, I encountered the following error: Run npm ci npm ERR! bindings not accessible from watchpack-chokidar2:fsevents npm ERR! A complete log of this run can be found in: npm ERR! /home/runner/.npm/_logs/2021-09-17 ...

What is preventing me from integrating angular-cookies into my application?

I'm struggling to resolve this issue where I can't seem to make it work. My aim is to integrate NgCookies (angular-cookies) into my application, but all I'm encountering are errors. This is what I currently have: JS files being included: ...

"Implementing a comment system using Node.js and MySQL: A comprehensive guide

Hey there! I have some data that I want to use to create a hierarchical data example. { id_commentForum: 1, id_user: 1, id_thread: 1, comment: 'This is the First Comment', parent: 0, created_at: Wed Jun 22 2016 13:36:38 G ...

Updating by clicking with auto-prediction feature

I have implemented an autosuggestion feature to display results from a database table while typing in an HTML field, and I am looking to utilize JavaScript to post another value from the same row where the autosuggested values are stored. https://i.stack. ...

Guide on parsing JSON data received from the frontend

Here is the HTML code that I am working with: <div id="loginform"> <form class="loginIn" name="loginform"> <input type="text" name="login"> <input type="password" name="password"> <input type="submit" value="Войт ...

Isolating an array from an object?

I am working with a component that receives props: The data received is logged on the console. https://i.sstatic.net/F3Va4.png What is the best way to extract the array from this object? Before I pass the array to my component, it appears like this: h ...

How can I trigger an Iframe JavaScript function from within my webpage?

I have an Iframe within my page, with the following JavaScript code: function getTotSeats(){ window.WebAppInterface.showToast(document.forms[0].txtSeat_no.value); return document.forms[0].txtSeat_no.value; } I would like to call the above Jav ...

Achieving a scrollable div with ng-repeat

I have implemented ng-repeat to showcase some messages, and I am attempting to create a scrollable "message_area" as the messages overflow naturally over time. However, my current code is not delivering the desired outcome. <div class="main_area"> ...

Creating a universal function to handle setTimeout and setInterval globally, inclusive of clearTimeout and clearInterval for all functions

Is it possible to create a universal setTimeout and setInterval function with corresponding clearTimeout and clearInterval for all functions while passing values to them? The situation is as follows: 1. More than 8 functions utilizing setInterval for act ...

Angular has the ability to round numbers to the nearest integer using a pipe

How do we round a number to the nearest dollar or integer? For example, rounding 2729999.61 would result in 2730000. Is there a method in Angular template that can achieve this using the number pipe? Such as using | number or | number : '1.2-2' ...

The npm http package exclusively includes a package.json without any accompanying JavaScript files

After installing an npm package that listed 'http' as a dependency, I also installed 'http'. However, all npm downloaded for 'http' was a package.json file that referenced a non-existent index.js file. Could it be that the ind ...

Tips for effectively utilizing the display:none property to conceal elements and permanently eliminate them from the DOM

While working on my website, I utilized CSS media queries to hide certain elements by using display: none. Even though this effectively hides the element from view, it still lingers in the DOM. Is there a way to completely eliminate the element from the ...

What is the proper method for utilizing colspan within the footerData of a jqGrid?

Are you looking to customize the footer of your jqgrid as shown in the example below? I am trying to set up a custom footer for my jqgrid similar to the one displayed above. I have already enabled the footerrow:true option and used $self.jqGrid("footerDat ...