gpt4 book ai didi

python - 在不使用 django.forms 的情况下在 Django 中上传多个文件

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:49 24 4
gpt4 key购买 nike

所以我创建了一个包含以下项目的表单

<input type="file" name="form_file" multiple/>

这告诉浏览器允许用户在浏览时选择多个文件。我遇到的问题是,在读取/写入正在上传的文件时,我只能看到最后一个文件,而不是所有文件。我很确定我以前见过这个,但没有运气搜索。这通常是我阅读的样子

if request.FILES:
filename = parent_id + str(random.randrange(0,100))
output_file = open(settings.PROJECT_PATH + "static/img/inventory/" + filename + ".jpg", "w")
output_file.write(request.FILES["form_file"].read())
output_file.close()

现在,如您所见,我没有遍历每个文件,因为我尝试了几种不同的方法,但似乎找不到其他文件(在对象等中)

我在这个 print(request.FILES["form_file"]) 中添加了并且只得到了最后一个文件名,正如预期的那样。是否有一些技巧可以获取其他文件?我坚持使用单个文件上传吗?谢谢!

最佳答案

根据您的文件元素 form_filerequest.FILES['form_file'] 中的值应该是一个文件列表。所以你可以这样做:

for upfile in request.FILES.getlist('form_file'):
filename = upfile.name
# instead of "filename" specify the full path and filename of your choice here
fd = open(filename, 'w')
fd.write(upfile['content'])
fd.close()

使用 block :

for upfile in request.FILES.getlist('form_file'):
filename = upfile.name
fd = open(filename, 'w+') # or 'wb+' for binary file
for chunk in upfile.chunks():
fd.write(chunk)
fd.close()

关于python - 在不使用 django.forms 的情况下在 Django 中上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3852744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com