File upload: create directory if it doesnt exist

后端 未结 1 970
渐次进展
渐次进展 2021-01-13 16:15

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,

相关标签:
1条回答
  • 2021-01-13 17:13

    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
                        });
                    });
                }
            });
        });
    });
    
    0 讨论(0)
提交回复
热议问题