I´m handling file uploads in NodeJS with formidable. This works for me. Now I want to structure the uploads a little more. I´m passing a field from angular with my uploads,
You are trying to rename the file before the directory was created. Also, using fs.exists is not advisable, and the function will be deprecated in the future.
I made some changes in your code, you could use the path
module to create the paths. Also, try creating the directory regardless if it already exists. If it exists, ignore the error code EEXIST.
The updated code:
// add this to the beggining
var path = require('path');
app.post('/uploads', function(req, res, next){
var form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, function(err, fields, files){
if (err) next (err);
fs.mkdir(path.resolve('uploads', fields.project_id), function (err) {
if (err && err !== 'EEXIST') {
next(err);
} else {
fs.rename(files.upload.path, path.resolve('uploads', fields.project_id, files.upload.name), function(err){
if(err) next (err);
res.render('profile.ejs',{
user:req.user
});
});
}
});
});
});