确保所有文件具有唯一名称的正确方法?

发布于 2024-10-28 22:06:37 字数 106 浏览 4 评论 0原文

我的网站有成员上传图像文件。

确保没有上传同名文件的最佳/最佳选择方法是什么?

我的想法是将会员 ID 合并到文件名中的某个位置并进行 md5 加密。还有其他想法吗?

I have members of my site uploading image files.

What are the top/best pick ways to make sure there is no file with the same name uploaded?

My idea was to incorporate the member ID somewhere in the filename and md5 encrypt it. Any other ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

诠释孤独 2024-11-04 22:06:37

如果您不担心文件名的可读性/长度,则使用 uniqid< /a> 在添加相关扩展名之前生成文件名的“基本”可能是最简单的解决方案。

(如果您可能在亚微秒内生成大量文件名,请启用more_entropy选项。)

If you're not worried about the readability/length of the filename, then using uniqid to generate the "base" of the filename prior to adding the relevant extension would probably be the simplest solution.

(If you're likely to be generating lots of filenames in a sub-microsecond period, enable the more_entropy option.)

佼人 2024-11-04 22:06:37

作为一点拼凑,您可以合并当前的纪元时间。更好的解决方案是使用一个 Singleton 类,它从递增的私有数据成员中发出标识符号。

As a bit of a kludge you can incorporate the current epoch time. A better solution would be to have a Singleton class which issues identifier numbers from an incremented private data member.

污味仙女 2024-11-04 22:06:37

使用 uniqid()@Middaparka 将是一种相当安全的方式,如果您不关心文件名的样子,这也是最好的方式。同一用户在同一微秒内对同一文件发出两个相同的请求的可能性极小。

如果您想保留原始文件名(这会带来 - 可解决但重要的 - 非 ASCII 字符问题),不断增加的计数器将是最安全的。

1_IMG0085.JPG
2_Lilies_and_pond.JPG
3_Awesome_Party_Pic.JPG

这样就不会发生碰撞,但是如果您想保证竞争条件安全,那么实现这样的计数器并不完全是微不足道的。

当用户上传图像时,您是否创建数据库记录?在这种情况下,您可以使用新创建的记录中的 ID 作为计数器变量。

Using uniqid() as shown by @Middaparka would be a reasonably safe way, and the best one if you don't care about what the file name looks like. It is extremely unlikely that the same user manages to make two identical requests with the same file in the same microsecond.

If you want to keep the original file names (which brings - solvable but important - issues with non-ASCII characters), an ever increasing counter would be the safest thing.

1_IMG0085.JPG
2_Lilies_and_pond.JPG
3_Awesome_Party_Pic.JPG

there is no chance of collisions this way, but such a counter is not entirely trivial to implement if you want to be race condition safe.

Are you creating a database record when a user uploads an image? In that case, you could use the ID from the newly created record as the counter variable.

梦毁影碎の 2024-11-04 22:06:37

只需将图像重命名为 GUID + 图像扩展名

just rename the image to a GUID + the image extension

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文