aboutsummaryrefslogtreecommitdiff
path: root/controllers/uploadController.js
diff options
context:
space:
mode:
authorBobby Wibowo <[email protected]>2018-03-18 19:21:04 +0700
committerBobby Wibowo <[email protected]>2018-03-18 19:21:04 +0700
commitdcb72734fe00fc9b7e060d66a4f247b7c9a56382 (patch)
treebf403d8fa3feb902075bcc667acf71586297d0f2 /controllers/uploadController.js
parentMerge pull request #78 from Shumatsu/no-powershell (diff)
downloadhost.fuwn.me-dcb72734fe00fc9b7e060d66a4f247b7c9a56382.tar.xz
host.fuwn.me-dcb72734fe00fc9b7e060d66a4f247b7c9a56382.zip
Patch to allow "retries" when generating random name
Diffstat (limited to 'controllers/uploadController.js')
-rw-r--r--controllers/uploadController.js18
1 files changed, 16 insertions, 2 deletions
diff --git a/controllers/uploadController.js b/controllers/uploadController.js
index 4e4b2e0..ec9e066 100644
--- a/controllers/uploadController.js
+++ b/controllers/uploadController.js
@@ -9,12 +9,26 @@ 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));
+ for (let i = 0; i < maxTries; i++) {
+ const name = randomstring.generate(config.uploads.fileLength) + path.extname(file.originalname);
+ try {
+ fs.accessSync(path.join(uploadDir, name));
+ console.log(`A file named "${name}" already exists (${i + 1}/${maxTries}).`);
+ } catch (err) {
+ // Note: fs.accessSync() will throw an Error if a file with the same name does not exist
+ return cb(null, name);
+ }
+ }
+ return cb('Could not allocate a unique file name. Try again?');
}
});