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, which is a project_id
. I want to create a folder in my uploads, named by this ID and write the files in it.
So I check if the directory exists, if not I create it with fs.mkdir
and then write the files to it. Trying this, I get a EINVAL, rename
error and a HTTP 500 status code.
This is my attempt, anybody got an idea how to fix this?
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.exists('uploads/' + fields.project_id + '/', function (exists){
if (exists) {
fs.rename(files.upload.path, 'uploads/' + fields.project_id + '/' +files.upload.name, function(err){
if (err) next (err);
res.render('profile.ejs',{
user: req.user
});
});
} else {
fs.mkdir('uploads/' + fields.project_id + '/', function (err){
if (err) next (err);
});
fs.rename(files.upload.path, 'uploads/' + fields.project_id + '/' + files.upload.name, function(err){
if(err) next (err);
res.render('profile.ejs',{
user:req.user
});
});
}
});
});
});
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
});
});
}
});
});
});
来源:https://stackoverflow.com/questions/30150646/file-upload-create-directory-if-it-doesnt-exist