Search code examples
javascriptnode.jssails.jsskipper

how to prevent the sailsjs file upload override


i'm trying to make a file uploader in sails.js, i have followed the docs and used the saveAs function as this:

create: function(req, res){
    var filename = req.file('file')._files[0].stream.filename;
    var file = req.file('file');
    file.upload({dirname: '../../assets/uploads/', saveAs: function (__newFileStream,cb) { cb(null, filename); }}, function(err, uploadedFiles){
        if(err){
            return res.json(err);
        }
        Archivo.create({nombre: uploadedFiles[0].filename, url: '/uploads/' + uploadedFiles[0].filename}).exec(function(err, uploadedFile){
            if(err){
                return res.json(err);
            }
            return res.json(uploadedFile);
        });

    });
},

the create controller uploads the file with the filename to the assets folder, and then creates a Archivo record

my problem is that i dont want to override the file if i upload it again, for example if i upload a file called image.jpg, and i upload it again i want the second time it renames it to image(1).jpg

someone knows how to do it?


Solution

  • The following when used in conjunction will give you the number of files that match the one your uploading based on the file name being uploaded. It will use regex to match based on this template image(1).jpg.

    So if you upload image.jpg it will look in your directory and find all files that match, all of the following will match.

    image.jpg
    image(1).jpg
    image(2).jpg
    image(3).jpg
    image(4).jpg
    

    So the system will return those files letting you know that you have 5 matching. Thus you can now use that number to rename the file your uploading at image(5).jpg.

    This should just get you started. It uses the NPM fs-finder library.

    var Finder = require('fs-finder');,
        filename = req.file('file')._files[0].stream.filename,
        directory = '../../assets/uploads/',
        filePreFix = filename.split('.')[0].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
        fileExtension = filename.split('.')[1].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')),
    
    
        var NumberOfMatchingFiles = 
            Finder
                .in(direcotry)
                .findFiles(
                    filePreFix + 
                    '(\([0-9]*\))*\' + 
                    fileExtension
                ).length
    

    Like I said, this will just get you started. You could have and issue where you delete image(2).jpg and thus you will only have 4 files and attempting to name your newly uploaded file as image(4).jpg will over write a file. You can check that against the list of files returned by fs-finder.