python - 在没有数据库的情况下保存在 Django 中上传的文件
问题描述
我正在尝试保存一个文件并从一个 html 文件中对其执行某些操作,我没有使用 django 表单,但我使用 django 作为后端,我不需要数据库,因为我不想保留任何文件。我尝试了 django 文档的指示。
.html 文件
<input type="file" id="face_files" name="face_files" multiple >
视图.py
def index(request):
if request.method == "GET":
return render(request, 'index.html')
if request.method == "POST":
form = InputForm(request)
call_form_function(form)
return render(request, 'index.html')
输入表单.py
class InputForm():
def __init__(self, request):
self.face_files = request.FILES.getlist('face_files')
# print('face_files= ', self.face_files)
self.face_name = request.POST.get('face_name')
# print('face_name= ', self.face_name)
def save_files(self):
import os
self.delete_temp()
folder = os.path.dirname(__file__) + '/static/temp/'+self.face_name
try:
os.mkdir(folder)
counter=1
for file in self.face_files:
# print(file)
destination=open(folder +"/face"+str(counter)+".jpg", 'wb+')
for chunk in file.chunks():
destination.write(chunk)
destination.close()
counter+=1
except:
with open(console_html_path, "w+") as f:
f.write(traceback.format_exc())
traceback.print_exc()
return folder
def do_function(self):
folder_path = self.save_files()
function(args, folder_path)
def call_form_function(form):
import threading
t1 = threading.Thread(target=form.do_function)
t1.start()
但我得到了错误
lib/python3.7/site-packages/django/core/files/uploadedfile.py", line 91, in chunks
self.file.seek(0)
ValueError: I/O operation on closed file.
我究竟做错了什么?
解决方案
您可以创建一个单独的函数来处理上传的文件。
def handle_uploaded_files(f):
with open(f'uploaded/folder/path/{f.name}', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
推荐阅读
- docker - Rancher(docker) 磁盘使用清理
- javascript - 多个输入的验证 | HTML - jQuery
- docker-compose - Traefik 2 网关超时
- asp.net - asp.net 中的 IIS 重写 URL 进入无限循环
- vue.js - Vue JS 在元素中加载动态组件
- rust - 代码出现 2015:第 5 天,第 2 部分未知误报
- neo4j - Neo4j:在流模式错误上测试“节点相似性”
- regex - 正则表达式超过最大行数
- matlab - MATLAB/Simulink R2019b 导数模块线性化为零
- javascript - 当 bot DM 用户收集响应时,消息收集器不会启动