nodejs上传图片代码:错误:ENOENT:没有这样的文件或目录

时间:2016-08-14 02:55:43

标签: node.js

我的节点上传文件代码是否有任何问题:

        app.post("/process/:year/:month", function(req,res){

        const dataDir = __dirname + '/public/data';
        const photoDir = dataDir + '/upload-logo';

        fs.stat(dataDir, function(err, stat) {
            if(err == null) {
                console.log('File exists');
                return;
            } else if(err.code == 'ENOENT') {
                // file does not exist
                fs.mkdirSync(dataDir);
                return;
            } else {
                console.log('Some other error: ', err.code);
                return;
            }
        });

        fs.stat(photoDir, function(err, stat) {
            if(err == null) {
                console.log('File exists');
                return;
            } else if(err.code == 'ENOENT') {
                // file does not exist
                fs.mkdirSync(photoDir);
                return;
            } else {
                console.log('Some other error: ', err.code);
                return;
            }
        });         

        try{
            //store the data to the database
            console.info('Received contact from ' + req.user.local.username + " <" + req.body.email + '>' );


            console.log('the file uploaded: ' , JSON.stringify(req.body));
            const form = new formidable.IncomingForm();
            form.parse(req,function(err,fields,files){

                if(err){return res.redirect(303, '/404');}
                const photo = files.photo;

                const timeDir = `${req.params.year}${req.params.month}`;
                const thedir = photoDir + `/${req.params.year}${req.params.month}`;//prevent uploading file with the same name

                fs.stat(thedir, function(err, stat) {
                    console.log('stat parts begins...');
                    if(err == null) {
                        console.log('File exists');
                        return;
                    } else if(err.code == 'ENOENT') {
                        // file does not exist
                        console.log('the file does not exist.now creating...');
                        fs.mkdirSync(thedir);

                        return;

                    } else {
                        console.log('Some other error: ', err.code);
                        return;
                    }
                });

                const photoName = Date.now() + photo.name; 
                const fullPath = thedir + '/' + photoName;

                console.log('the dir is :' + thedir);
                console.log(photo.name,photo.path,fullPath);
                fs.renameSync(photo.path, fullPath);//rename or move the file uploaded;and photo.path is the temp file Formidable give

                if(req.user){
                    function saveFileInfo(){

                        const user = req.user;
                        user.local.logo = timeDir + '/' + phontoName;
                        user.save(function(err){
                            if(err){throw err}
                            req.flash('success','Upload your logo successfully');
                            res.redirect('/user/profile');
                        });

                    }
                  //  saveFileInfo('upload-photo', fields.email,req.params.year,fields.params.year,fields.params.month,path);
                }else{
                    console.log('user not login');
                    req.flash('eror','You need to login first to upload your logo');
                    res.redirect(303, '/login');
                }

                //console.log('received fields:', fields);
                //console.log('received files:', photo.name);

            });

            req.flash('success', 'Uploading successfully!')

            return res.xhr ? res.render({success: true}) :
                res.redirect(303, '/success');
        } catch(ex){
            return res.xhr ?
                res.json({err: 'Database error.'}):
                res.redirect(303, '/db-error');
        }
    });

上面的代码给了我错误:

fs.js:681
  return binding.rename(pathModule._makeLong(oldPath),
                 ^

Error: ENOENT: no such file or directory, rename '/var/folders/vq/cdlwyckx68zdf586bd3c789h0000gn/T/upload_2e1c480cfbdf943fe1dd45dbb2ccc37e' -> '/Users/frank25184/Desktop/nodejs/nodeForm-team/public/data/upload-logo/20167/147114292564330682361630021890.jpg'
    at Error (native)
    at Object.fs.renameSync (fs.js:681:18)
    at /Users/frank25184/Desktop/nodejs/nodeForm-team/routes.js:496:24
    at IncomingForm.<anonymous> (/Users/frank25184/Desktop/nodejs/nodeForm-team/node_modules/formidable/lib/incoming_form.js:105:9)
    at emitNone (events.js:67:13)
    at IncomingForm.emit (events.js:166:7)
    at IncomingForm._maybeEnd (/Users/frank25184/Desktop/nodejs/nodeForm-team/node_modules/formidable/lib/incoming_form.js:553:8)
    at /Users/frank25184/Desktop/nodejs/nodeForm-team/node_modules/formidable/lib/incoming_form.js:230:12
    at WriteStream.<anonymous> (/Users/frank25184/Desktop/nodejs/nodeForm-team/node_modules/formidable/lib/file.js:70:5)
    at WriteStream.g (events.js:260:16)
    at emitNone (events.js:72:20)
    at WriteStream.emit (events.js:166:7)
    at finishMaybe (_stream_writable.js:481:14)
    at afterWrite (_stream_writable.js:355:3)
    at onwrite (_stream_writable.js:345:7)
    at WritableState.onwrite (_stream_writable.js:89:5)
我尝试了半天。但没有成功。总是显示此错误。但我确实有fs.stat()函数来制作thedir目录 任何人都知道这里发生了什么,谢谢

1 个答案:

答案 0 :(得分:0)

我不清楚你想要的商店上传文件,所以可能会有问题。

let async = require('async');

const dataDir = __dirname + '/public/data';
const tempDir = __dirname + '/public/temp';
...
function checkDir(dir, callback) {
    fs.stats(dir, function(err, stats) {
        if (!err)
            return callback();

        if (stats.isFile()) 
            return callback(new Error(dir + ' is file'));

        if (err.code != 'ENOENT')       
            return callback(err);

        fs.mkdir(dir, callback);
    })
}
...
async.each([dataDir, tempDir], checkDir, (err) => throw err);
...
function isAuth(req, res, next) {
    if (req.user)
        return next();

    console.log(req.url, ': user not login' );
    req.flash('error','You need to login first to upload your logo');
    res.redirect(303, '/login');    
}

// Check login user in middleware isAuth
// Error pass by Error handler middleware
app.post("/process/:year/:month", isAuth, function(req, res, next){ 
    console.info('Received contact from ...');
    console.log('the file uploaded: ', JSON.stringify(req.body));

    const form = new formidable.IncomingForm();
    form.uploadDir = tempDir;
    form.parse(req, function (err, fields, files) {
        if(err)
            return next (err);

        const photo = files.photo;
        const targetDir = dataDir + `/${req.params.year}${req.params.month}/`;
        const targetPath = targetDir + '/' + targetname + Date.now() + photo.name; // ???

        async.Series([
            function(callback) { checkDir(targetDir, callback); },
            function(callback) { fs.rename(tempDir + '/' + photo, targetPath, callback); },
            function(callback) { req.user.local.logo=targetPath; req.user.save(callback); }
        ], function (err) {
            if (err)
                return next(err);

            req.flash('success', 'Uploading successfully!')
            return res.xhr ? 
                res.render({success: true}) :
                res.redirect(303, '/success'); //? res.redirect('/user/profile');
        });
    });
});     

// send error to user
app.use(function(err, req, res, next) {
    req.flash('error', err.message);
    return res.xhr ? ...
})