在Django中保存FileField的原始文件名 [英] Keeping Original Filename for FileField in Django

查看:151
本文介绍了在Django中保存FileField的原始文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保留Django中的 UploadedFile 的原始文件名,该文件的名称位于 FileField 。现在我正在观察到,如果两个文件具有相同的名称,则上传的第一个文件保留其原始名称,但是第二次上传具有该名称的文件时,它会附加一个随机字符串,以使文件名独一无二。一个解决方案是为模型添加一个附加字段: Django:如何将原始文件名保存在FileField?保存原始文件名Django与FileField ,但这些解决方案看起来不是最佳的,因为它们需要更改 Model 字段。



另一种方法是在文件前面添加一个随机目录路径,确保在给定的目录中,文件名是唯一的,并允许 basename 保持不变。执行此操作的一种方法是传递一个可执行的 upload_to 。另一个选择是将 FileField 子类化,并覆盖 get_filename ,以将 basename 允许调用者使用前置路径传入文件名。如果我想要使用 ImageField ,那么后一个选项并不理想,因为我也必须将其子类化。

解决方案

查看通过附加随机字符串实际生成唯一文件名的代码,看起来这个问题的最佳解决方案可能是子类存储 class < a>正在使用和覆盖 get_available_name 方法,通过前面的目录创建唯一的文件名,而不是将字符串发布到基本名称。


I would like to keep the original file name of an UploadedFile in Django that has its location stored in a FileField. Right now I am observing that if two files have the same name, the first file uploaded keeps its original name but the second time a file with that name is uploaded, it has a random string appended to make the file name unique. One solution is to add an additional field to the model: Django: How to save original filename in FileField? or Saving Original File Name in Django with FileField but these solutions seem suboptimal as they require changing the Model fields.

An alternative would be to prepend a random directory path to the front of the file make sure that in a given directory the file name is unique and allowing the basename to remain unchanged. One way to do this would be to pass in a callable upload_to that does just that. Another option would be to subclass FileField and override get_filename to not strip the input filename to the basename allowing the caller to pass in a filename with a prepended path. The latter option is not ideal if I want to use an ImageField as I would have to subclass that as well.

解决方案

In looking at the code that actually generates the unique filename by appending the random string, it looks like the best solution to this problem might be to subclass the Storage class in-use and override get_available_name method to create unique filenames by prepending a directory rather than post-pending the string to the base name.

这篇关于在Django中保存FileField的原始文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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