someGuy
someGuy

Reputation: 73

How to handle file uploads when a file with same name exists using node js

I am using formidable node module for uploading the file. Here is my .jade code

  form#uploadForm(enctype='multipart/form-data', method='POST', action='/upload')
    input#uploadTestSheet(type='file', name='uploadTestSheet', accept='.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel')
    button(type='submit') Submit

The files are getting uploaded but if a file already exists in the directory and then a user is trying to add a file with the same name then the new file is not getting uploaded. Here is my Server

var fs = require('node-fs-extra');
           var formidable = require('formidable');

    app.use(bodyparser({defer: true}));
    app.post('/upload',function (req, res, next) {

        var form = new formidable.IncomingForm();

        form.uploadDir =__dirname +"/uploads";
        form.keepExtensions = true;     
        form.parse(req, function(err, fields, files) {
              fs.rename(files.uploadTestSheet.path,__dirname +'/uploads'+files.uploadTestSheet.name, function(err) {
           if (err){
               res.render('ManualMode',{data:{id:req.user.id, hash:req.user.hash, nodePollInterval:req.user.nodePollInterval}});
               console.log("cannot upload: "+err);
           }  
           });
           res.render('index',{data:{id:req.user.id, hash:req.user.hash, nodePollInterval:req.user.nodePollInterval}});
       });

});

Upvotes: 0

Views: 1970

Answers (1)

m-a-r-c-e-l-i-n-o
m-a-r-c-e-l-i-n-o

Reputation: 2672

The fs.rename method follows linux conventions, so it should be overwriting the files in the directory. This leads me to think that maybe your problem is in the browser. Chrome for instance, will refuse to upload files of the same name without first clearing the value property in the input field. In your case, assuming your uploading is asynchronous, this would do:

document.getElementById('uploadTestSheet').value = ''; // after each upload

If you have verified that this is not the issue, try deleting the potentially existent file before renaming it, something along the lines of:

...
var newFilename = __dirname + '/uploads' + files.uploadTestSheet.name
try {
  fs.unlinkSync(newFilename)
} catch (e) {
  if (e.code !== 'ENOENT')
    throw err; 
}

fs.rename(files.uploadTestSheet.path, newFilename, function(err) {
...

I hope that helps!

Upvotes: 2

Related Questions