my code is ditto as the the reference
You need to create some kind of uniuqe ID to append to the filename, before saving the file.
This can be done with something like:
from uuid import uuid4
def make_unique(string):
ident = uuid4().__str__()[:8]
return f"{ident}-{string}"
Which can be used to add 8 random characters to the start of a string:
>>> make_unique('something.txt')
'aa659bb8-something.txt'
To use this in the upload code, just run the filename through that function before you save. Be sure to put the filename through the secure_filename
function first though:
if file and allowed_file(file.filename):
original_filename = secure_filename(file.filename)
unique_filename = make_unique(original_filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], unique_filename))
Although this works for the purpose of avoiding duplicates, in a larger application you may wish to extend this approach.
If you store the values of original_filename
and unique_filename
in the database, then this allows you to do the following in the download route:
from flask import send_file
# ...
f = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
send_file(f, attachment_filename=original_filename)
This has the advantage that the file is stored on your server with a unique identifier, but the user would never know this, as the file is served back to them with the originally uploaded filename.
Infact you may wish to go further, and simply save the file on your end with a full uuid string; instead of using the make_unique
function above, change that third line to:
unique_filename = uuid4().__str__()
This will still serve the file with the correct mimetype, as send_file
guesses the mimetype based on the provided attachment_filename
.