Tuesday, 2 May 2017

nodejs multer file upload, path contains double slashes

I am working on image upload via nodejs and multer module and this is the code im using:

app.post('/upload', upload.single('file'), function(req, res, next) {
    var tmp_path = req.file.path,
        target_path = __dirname + '/public/uploads/' + req.file.originalname,

        src = fs.createReadStream(tmp_path),
        dest = fs.createWriteStream(target_path);

    src.pipe(dest);
    fs.unlink(tmp_path); //deleting the tmp_path

    src.on('end', function() {
        res.json({
            success: true,
            file: '/uploads/' + req.file.originalname
        });
    });

    src.on('error', function(err) {
        console.log('err', err);
        res.json({
            success: false
        });
    });
});

The problem is that sometimes (it occures randomly) error callback is triggered, with this contents:

enter image description here

So it looks like additional slashes are added to the path which causes script not to find temp location and returns error, maybe someone encountered this problem and can help ;)



via Patrick Mevia

No comments:

Post a Comment