diff options
| author | Kana <[email protected]> | 2018-03-19 07:53:32 -0300 |
|---|---|---|
| committer | GitHub <[email protected]> | 2018-03-19 07:53:32 -0300 |
| commit | 015738821780367ec4c476c50e6e50f44484d244 (patch) | |
| tree | b12b2a86977be28eb3352356fbf2be8476075f22 /controllers | |
| parent | Merge pull request #78 from Shumatsu/no-powershell (diff) | |
| parent | Uses async (diff) | |
| download | host.fuwn.me-015738821780367ec4c476c50e6e50f44484d244.tar.xz host.fuwn.me-015738821780367ec4c476c50e6e50f44484d244.zip | |
Merge pull request #85 from BobbyWibowo/pr-retry-names
Patch to allow "retries" when generating random name
Diffstat (limited to 'controllers')
| -rw-r--r-- | controllers/uploadController.js | 19 |
1 files changed, 16 insertions, 3 deletions
diff --git a/controllers/uploadController.js b/controllers/uploadController.js index 4e4b2e0..51c0cf4 100644 --- a/controllers/uploadController.js +++ b/controllers/uploadController.js @@ -9,12 +9,25 @@ const utils = require('./utilsController.js'); const uploadsController = {}; +// Let's default it to only 1 try +const maxTries = config.uploads.maxTries || 1; +const uploadDir = path.join(__dirname, '..', config.uploads.folder); + const storage = multer.diskStorage({ destination: function(req, file, cb) { - cb(null, path.join(__dirname, '..', config.uploads.folder)); + cb(null, uploadDir); }, - filename: function(req, file, cb) { - cb(null, randomstring.generate(config.uploads.fileLength) + path.extname(file.originalname)); + filename: function(req, file, cb) { + const access = i => { + const name = randomstring.generate(config.uploads.fileLength) + path.extname(file.originalname); + fs.access(path.join(uploadDir, name), err => { + if (err) return cb(null, name); + console.log(`A file named "${name}" already exists (${++i}/${maxTries}).`); + if (i < maxTries) return access(i); + return cb('Could not allocate a unique file name. Try again?'); + }); + }; + access(0); } }); |