Browse Source

Patch to allow "retries" when generating random name

Bobby Wibowo 6 years ago
parent
commit
dcb72734fe
2 changed files with 23 additions and 2 deletions
  1. 7 0
      config.sample.js
  2. 16 2
      controllers/uploadController.js

+ 7 - 0
config.sample.js

@@ -62,6 +62,13 @@ module.exports = {
 		fileLength: 32,
 
 		/*
+			This option will limit how many times it will try to generate random names
+			for uploaded files. If this value is higher than 1, it will help in cases
+			where files with the same name already exists (higher chance with shorter file name length).
+		*/
+		maxTries: 1,
+
+		/*
 			NOTE: Thumbnails are only for the admin panel and they require you
 			to install a separate binary called graphicsmagick (http://www.graphicsmagick.org)
 			for images and ffmpeg (https://ffmpeg.org/) for video files

+ 16 - 2
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?');
 	}
 });