首页 > 解决方案 > 在没有数据库的情况下保存在 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.

我究竟做错了什么?

标签: pythonpython-3.xdjangodjango-formsdjango-views

解决方案


您可以创建一个单独的函数来处理上传的文件。

def handle_uploaded_files(f):
    with open(f'uploaded/folder/path/{f.name}', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

推荐阅读