1

I went through hundreds of pages for several days without success and here is my problem.

I use the MEAN stack and at this point I have a simple form that works very well to save a "name" field to a MongoDB collection. Now, I would like, client-side, add an image upload and, on form submit, store the image on my server and finally save the "name" field and the image path to the MongoDB collection.

AngularJS side, I tried using ng-file-upload with multer server-side. I have done well to operate for the upload of the file but only that. But after hundreds of tests, I despair. Here is an extract of my original code without file upload.

Server side

sections.server.model

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var SectionSchema = new Schema({
    name: {
        type: String,
        default: '',
        trim: true,
        required: true,
        unique: true
    },
    image: {
        type: String,
        default: ''
    }
});
mongoose.model('Section', SectionSchema);

sections.server.controller

exports.create = function (req, res) {
    var section = new Section(req.body);
    section.save(function (err) {
        if (err) {
            return res.status(400).send({
                message: getErrorMessage(err)
            });
        } else {
            res.json(section);
        }
    });
};

sections.server.routes

var sections = require('../../app/controllers/sections.server.controller');

module.exports = function (app) {
    app.route('/api/sections')
        .post(sections.create);
};

Client side

sections.client.module

'use strict';
var sections = angular.module('sections', []);

sections.client.controller

'use strict';
angular.module('sections')
    .controller('SectionsController',
        ['$scope', '$routeParams', '$location', 'Sections'
            function ($scope, $routeParams, $location, Sections) {
                $scope.create = function () {
                    var section = new Sections({
                        name: this.name
                    });

                    section.$save(function (response) {
                        $location.path('sections/' + response._id);
                    }, function (errorResponse) {
                        $scope.error = errorResponse.data.message;
                    });
                };

            }]);

sections.client.routes

angular.module('sections').config(['$routeProvider', function ($routeProvider) {
            $routeProvider
                .when('/sections', {
                    controller: 'SectionsController',
                    templateUrl: 'sections/views/list-sections.client.view.html'
                })
                .when('/sections/create', {
                    controller: 'SectionsController',
                    templateUrl: 'sections/views/create-section.client.view.html'
                })
                .otherwise({
                    redirectTo: '/'
                });
        }]);

sections.client.service

'use strict';
angular.module('sections').factory('Sections', ['$resource', function ($resource) {
    return $resource('api/sections/:sectionId', {
        sectionId: '@_id'
    }, {
        update: {
            method: 'PUT'
        }
    });
}]);

create-section.client.view

<section>
    <h1>New Article</h1>   
    <form data-ng-submit="create()" novalidate>
        <div>
            <label for="name">Nom du rayon</label>  
            <div>
                <input type="text" data-ng-model="name" id="name" placeholder="Name" required>
            </div>
        </div>  
        <div>
            <input type="submit">
        </div>
        <div data-ng-show="error"><strong data-ng-bind="error"></strong></div>
    </form> 

</section>

Now, from this can anyone help me to add the image upload in the form and then save the field name and the image path in MongoDB.

Note that I want to reuse the upload mechanism in other forms of my app. I had the idea of switching a generic middleware function in the road-side server which calls multer and return the image path to my sections.create function for MongoDB storing, something like that :

module.exports = function (app) {
    app.route('/api/sections')
        .post(uploads.upload, sections.create);

But I've never managed to pass the file in the POST from AngularJS request.

Thank you so much for all your ideas, your help and possibly an example of code that works.

4
  • would you like code that can submit form data along with your image or images and then after uploading file/files it'll save your other data along with image name in mongodb? Commented Mar 1, 2016 at 21:55
  • Thank you very much for your interest, the result should probably be the same? However, perhaps should I first upload the image (like this I can firstly display it in the form) before storing other data and the path to the image in mongoDB Commented Mar 1, 2016 at 22:07
  • even without storing the image you can show a snippet to the user and even if you decide to upload it first then it is easier, just send the image name as a response back to your frontend from node and then send it along with other data. Now tell me what exactly do you want in particular because you have pasted a lot of codes, come to the exact pain point. :) Commented Mar 1, 2016 at 22:53
  • Thanks a lot for your answers. I found a solution with FormData handling in my ngResource service and then posting request with my upload middleware multer-based. So, data are submited along with my file. Commented Mar 6, 2016 at 12:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.