Si un fichier existe déjà, ne pas l’écraser mais en créer un nouveau
authorOlivier Tétard <olivier.tetard@miskin.fr>
Fri, 13 Nov 2015 10:00:57 +0000 (11:00 +0100)
committerOlivier Tétard <olivier.tetard@miskin.fr>
Fri, 13 Nov 2015 10:00:57 +0000 (11:00 +0100)
femtoblackweb.py

index c581705..aafd48d 100644 (file)
@@ -51,16 +51,27 @@ def upload_file():
     if request.method == 'POST':
         f = request.files['file']
 
-        result = {
-            'name': f.filename,
-            'type': f.mimetype,
-        }
-        
+        result = {}
+
         if allowed_file(f.filename):
             filename = secure_filename(f.filename)
+            (basename, ext) = os.path.splitext(filename)
+
             dst_file = os.path.join(app.config['UPLOAD_FOLDER'], filename)
+
+            # Si le fichier existe déjà, on rajoute un compteur avant
+            # l’extension.
+            n = 0
+            while os.path.isfile(dst_file):
+                n += 1
+                filename = "{} ({}){}".format(basename, n, ext)
+                dst_file = os.path.join(app.config['UPLOAD_FOLDER'], filename)
+
             f.save(dst_file)
             result['size'] = os.path.getsize(dst_file)
+            result['name'] = filename
+            result['type'] = f.mimetype
+
         else:
             result['size'] = 0
             result['error'] = 'Filetype not allowed'
@@ -73,12 +84,12 @@ def upload_file():
 @app.route('/download/<filename>')
 def download(filename):
     return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
-    
+
 @app.route('/analyze/<filename>')
 def analyze_file(filename):
     f = os.path.join(app.config['UPLOAD_FOLDER'], filename)
 
-    if os.path.exists(f):    
+    if os.path.exists(f):
         return render_template('analyze_file.html', filename=filename)
 
     else:
@@ -158,7 +169,7 @@ def test_disconnect():
 
 
 
-    
+
 if __name__ == "__main__":
     socketio.run(app)
     #app.run(debug=True)