I'm using MEAN.IO for developing a webapp.
At this momento, i'm trying to accomplish an uploader for images. For that, i'm using angular-file-upload and it seems to work pretty well.
My problem is at server side. I have something like this:
exports.upload = function(req, res, next) {
console.log(root.process.env.PWD); // OK
var uploadPath = path.normalize(root.process.env.PWD + '/uploads'),
file = req.files.file, // file itself
data = new Buffer(''),
imgURL = undefined; // public URL to show the pic
console.log(file.name); // OK
console.log(file.path); // OK
console.log(uploadPath); // OK
if( !fs.existsSync(uploadPath) ){
console.log('Creating directory.');
fs.mkdirSync(uploadDir, 0755);
}
req.on('data', function(chunk) {
console.log('Receiving data');
data = Buffer.concat( [data, chunk] );
})
.on('end', function() {
console.log('Data received');
// Writing file to hard disk
fs.writeFile(uploadPath, data, function(err) {
if ( err ) {
console.log('Error saving the uploaded header image.');
return res.status(500).json({
error: 'Cannot upload the image'
});
}
console.log('Header image properly uploaded and saved.')
// Creating the public URL to send it out
imgURL = '/uploads/' + file.name;
console.log(imgURL);
res.json(imgURL);
});
});
console.log('Finished');
};
When I put the comment // OK in a console.log is because it prints what it must print (so works as expected).
My main problem is
console.log('Receiving data');
and
console.log('Data received');
are not printed, so the execution flow totally ignores both req.on() methods. I have no doubt why, but i'm sure it must be something i have forgotten.
The
console.log('Finished');
is printed properly, so the execution finishes without any kind of problem or exception.
Thanks in advance!
EDIT:
In routes.js, I had added this (i forgot to mention it):
'use strict';
var Media = require('../controllers/Media'),
multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var hasAuthorization = function(req, res, next) {
if (!req.user.isAdmin) {
return res.send(401, 'User is not authorized.');
}
next();
};
module.exports = function(Media, app, auth, database) {
app.route('/media/upload/header')
.post(multipartMiddleware, auth.requiresLogin, hasAuthorization, Media.upload);
};
Well I found myself in a similar situation I just forgot to set up a middleware for requesting file, in this case busboy did the trick!
in your express config just do this:
var busboy = require('connect-busboy');
then
app.use(busboy());
in your controller:
exports.upload = function(req, res) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file',function(fieldname, file, filename, encoding, mimetype){
console.log('uploading file:'+mimetype);
file.on('data',function(data){
});
file.on('end', function(){
});
});
};