Search code examples
javascriptnode.jsfile-uploadmultipartformidable

Formidable multi-file upload - ENOENT, no such file or directory


I know this question has been asked but my mind has been blown by my inability to get this working. I am trying to upload multiple images to my server with the following code:

var formidable = require('formidable');
var fs = require('fs');

...

router.post('/add_images/:showcase_id', function(req, res){
    if(!admin(req, res)) return;
    var form = new formidable.IncomingForm(),
    files = [];


    form.uploadDir = global.__project_dirname+"/tmp";
    form.on('file', function(field, file) {
        console.log(file);

        file.image_id = global.s4()+global.s4();
        file.endPath = "/img/"+file.image_id+"."+file.type.replace("image/","");
        files.push({field:field, file:file});
    });
    form.on('end', function() {
        console.log('done');
        console.log(files);
        db.get("SOME SQL", function(err, image_number){
            if(err){
                console.log(err);
            }
            var db_index = 0;
            if(image_number) db_index = image_number.image_order;
            files.forEach(function(file, index){
                try{
                    //this line opens the image in my computer (testing)
                    require("sys").exec("display " + file.file.path);
                    console.log(file.file.path);
                    fs.renameSync(file.file.path, file.file.endPath);
                }catch (e){
                    console.log(e);
                }
                db.run( "SOME MORE SQL"')", function(err){
                    if(index == files.length)
                        res.redirect("/admin/gallery"+req.params.showcase_id);
                });
            });
        });
    });
    form.parse(req);
});

The line that opens the image via system calls works just fine, however I continue to get: Error: ENOENT, no such file or directory '/home/[username]/[project name]/tmp/285ef5276581cb3b8ea950a043c6ed51' by the rename statement.

the value of file.file.path is: /home/[username]/[project name]/tmp/285ef5276581cb3b8ea950a043c6ed51

I am so confused and have tried everything. What am I doing wrong?


Solution

  • Probably you get this error because the target path does not exist or you don't have write permissions.

    The error you get is misleading due to a bug in nodejs, see:

    Consider adding:

    console.log(file.file.endPath);
    

    before the fs.renameSync call and check if the target path exist and is writable by your application