Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - How should I handle duplicate filenames when uploading a file with Flask

I recently came across this question and answer https://stackoverflow.com/a/44926557/12322095 regarding Flask file uploads.

This worked perfectly fine until I uploaded an image with the same name again. It didn't change the image or overlayed it.

My question here is what if a user uploads an image with the same name, is there any way we could show an error message or maybe automatically change the name to something else.

For automatic changing the name, I researched and it can be done via resolve_conflict but I couldn't understand how to implement it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...