如何在Django中获取上传文件的名称 [英] How to get the name of uploaded file in Django
问题描述
我已经看到一些有关此问题的信息,但这些问题无法解决我的问题,这就是为什么我要提出一个新问题.请不要将此标记为重复项!
I have seen some question about it already but these couldn't solve my issue, that's why I'm asking a new question.So, don't mark this as duplicate, please!
使用Python(3.6)&Django(1.10)我正在尝试获取上传文件的名称,但返回
Using Python(3.6) & Django(1.10) I'm trying to get the name of uploaded file, but it returns
AttributeError:"NoneType"对象没有属性名称"
这是我尝试过的:来自 models.py
Here's what I have tried: From models.py
sourceFile = models.FileField(upload_to='archives/', name='sourceFile', blank=True)
通过 HTML模板:
<div class="form-group" hidden id="zipCode">
<label class="control-label" style="font-size: 1.5rem; color: black;">Select File</label>
<input id="sourceFile" name="sourceFile" type="file" class="file" multiple
data-allowed-file-extensions='["zip"]'>
<small id="fileHelp" class="form-text control-label" style="color:black; font-size: .9rem;">
Upload a Tar or Zip
archive which include Dockerfile, otherwise your deployment will fail.
</small>
</div>
来自 views.py :
if form.is_valid():
func_obj = form
func_obj.sourceFile = form.cleaned_data['sourceFile']
func_obj.save()
print(func_obj.sourceFile.name)
这是怎么了?
请帮帮我!
提前谢谢!
推荐答案
要获取文件名,只需使用request.FILES字典(我假设只有1个文件正在上传)
To get the filename, you simply use the request.FILES dictionary (I assume that there is only 1 file being uploaded)
示例:
try:
print(next(iter(request.FILES))) # this will print the name of the file
except StopIteration:
print("No file was uploaded!")
请注意,这要求文件通过POST方法作为表单的一部分发送.
Note that this requires that the files were sent as a part of a form by the POST method.
要将其名称更改为随机字符串,建议使用 uuid.uuid4
,因为这会生成一个随机字符串,该字符串非常不可能与已经存在的任何内容发生冲突.另外,您需要通过提供生成名称的功能来编辑 sourceFile
模型的 upload_to =
部分:
To change their name to a random string, I recommend uuid.uuid4
, as this generates a random string that is VERY unlikely to collide with anything already there. Also, you need to edit your upload_to=
section of your sourceFile
model by providing a function to generate the name:
# In models.py
def content_file_name(instance, filename):
filename = "{}.zip".format(str(uuid.uuid4().hex))
return os.path.join('archives', filename)
# later....
sourceFile = models.FileField(upload_to=content_file_name, name='sourceFile', blank=True)
希望这会有所帮助!
这篇关于如何在Django中获取上传文件的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!