naik3 naik3 - 3 months ago 26
HTML Question

Return undefined answer from multer

I am using multer in my nodejs application for uploading files. And angularjs for the front end part. Once I click upload image, on the console I am getting undefined answer. Can any one help me to solve the problem.
Here I am pasting the code.
server.js

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;

var multer = require('multer');
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/upload/');
},
filename:function(req,file,cb){
cb(null,file.originalname);
}
});

var upload = multer({storage: storage});

app.set('views', __dirname + '/views');

app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });

app.use(express.static('public'));

app.get('/',function(req,res){
res.render('index',{ title: 'Upload image' });
});

app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})


And here is my app.js angularjs code

var app = angular.module('app',['ui.router','ui.bootstrap','ngAnimate']);
$scope.img={};
app.controller('Ctrl',function ($scope,$http){
$scope.loadImage = function(){
$http.post('/loadImage',$scope.img).success(function(data){
console.log('Posted successfully');
}).error(function(data){
console.error('error');
})
};


And my HTML code:

<form ng-submit="loadImage()" enctype="multipart/form-data">
<input type="file" name="file" multiple />
<input type="submit" value="Upload Image" name="submit" />
</form>


On the console I am getting Undefined and Inside post. And on the browser console I am getting posted successfully Can any one please help me to solve this. Instead of undefined I should get loaded file information.

Answer

This how i used Multer to upload an image

var multer = require('multer');

exports.loadImage = function (req, res) {
var upload = multer({
        inMemory: true,
        limits: {fileSize: 1024 * 1024 }
    }).single('newPicture');

upload(req, res, function (uploadError) {
    if (uploadError) {
        return res.status(400).send({ message: 'errorUploadingPicture' });
    }
    else {
        var profileImage = 'No data uploaded';
        // this is where the photo data is
        if (req.file && req.file.buffer) {
            profileImage = req.file.buffer;
        }
        return res.json(profileImage );           
    }
});

};