File upload: create directory if it doesnt exist

我的梦境 提交于 2019-12-01 08:28:01

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
                    });
                });
            }
        });
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!