From: Olivier Tétard Date: Fri, 13 Nov 2015 10:00:57 +0000 (+0100) Subject: Si un fichier existe déjà, ne pas l’écraser mais en créer un nouveau X-Git-Url: http://olivier.miskin.fr/git/?a=commitdiff_plain;h=cbdd3dfe3dabd568e8a8bf3af469c47699864f22;p=femtoblackweb.git Si un fichier existe déjà, ne pas l’écraser mais en créer un nouveau --- diff --git a/femtoblackweb.py b/femtoblackweb.py index c581705..aafd48d 100644 --- a/femtoblackweb.py +++ b/femtoblackweb.py @@ -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/') def download(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) - + @app.route('/analyze/') 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)