[Flask] User uploads file naming conflicts

Clint Moyer contact at clintmoyer.com
Thu Jan 5 14:05:33 EST 2017


Hello everyone,

My desire is to have a simple upload form for images, but I am not
sure how to manage naming conflicts.

My start point was http://flask.pocoo.org/docs/0.12/patterns/fileuploads/

Which then gets me to here:
[code: Python]

MEDIA_DIR = my media directory
input_name = name field from file input form

img = request.files[input_name]
img_name = secure_filename(img.filename)
path = os.path.join(MEDIA_DIR, img_name)
img.save(path)

[/code]

I have no problem submitting new images with this,
werkzeug.FileStorage is the suggested object to use, but it seems the
save() method fails silently. Trying this myself by uploading new
image with the same name, the file was not uploaded. Not very friendly
to newcomers, but sensible by Flask 'batteries not included'
standards.

I understand this is because the method catches the error:

[code: Python]
# https://github.com/pallets/werkzeug/blob/master/werkzeug/datastructures.py
try:
     shutil.copyfileobj(self.stream, dst, buffer_size)
[/code]

My question is, what is best practice for managing naming conflicts?
Should I iterate existing files and check for matching? Is there a
useful numerical system I could use to append filenames?

Thanks in advance,

--
Clint


More information about the Flask mailing list