使用 Flask 上传文件时如何处理重复的文件名 [英] How should I handle duplicate filenames when uploading a file with Flask

查看:26
本文介绍了使用 Flask 上传文件时如何处理重复的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了这个问题并回答了 https://stackoverflow.com/a/44926557/12322095 关于 Flask文件上传.

这一切都很好,直到我再次上传了同名的图像.它没有改变图像或覆盖它.

我的问题是,如果用户上传同名图片,我们有什么办法可以显示错误消息或自动将名称更改为其他名称.

对于自动更改名称,我研究过,可以通过resolve_conflict来完成,但我不明白如何实现.

解决方案

我的代码同上作为参考

在保存文件之前,您需要创建某种 uniuqe ID 以附加到文件名.

这可以通过以下方式完成:

from uuid import uuid4def make_unique(字符串):ident = uuid4().__str__()返回 f"{ident}-{string}";

在字符串的开头添加唯一的 UUID:

<预><代码>>>>make_unique('something.txt')'f374b80c-b09e-468f-adc6-3d9df175cee7-something.txt'

要在上传代码中使用它,只需在保存之前通过该函数运行文件名.请务必先通过 secure_filename 函数输入文件名:

 如果文件和 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))


尽管这样做是为了避免重复,但在更大的应用程序中,您可能希望扩展这种方法.

如果您将original_filenameunique_filename 的值存储在数据库中,那么这允许您在下载路径中执行以下操作:

from flask import send_file# ...f = os.path.join(app.config['UPLOAD_FOLDER'],unique_filename)发送文件(f,附件文件名=原始文件名)

这样做的好处是文件以唯一标识符存储在您的服务器上,但用户永远不会知道这一点,因为文件以最初上传的文件名返回给他们.

事实上,您可能希望更进一步,只需使用 UUID 字符串将文件保存在您的末尾,而不是附加文件名;不要使用上面的 make_unique 函数,而是将第三行更改为:

unique_filename = uuid4().__str__()

这仍将提供具有正确 mimetype 的文件,因为 send_file 根据提供的 attachment_filename 猜测 mimetype.

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.

解决方案

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__()
    return f"{ident}-{string}"

Which adds an unique UUID to the beginning of the string:

>>> make_unique('something.txt')
'f374b80c-b09e-468f-adc6-3d9df175cee7-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.

In fact you may wish to go further, and simply save the file on your end with the UUID string, rather than appending the filename; 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.

这篇关于使用 Flask 上传文件时如何处理重复的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆