保存在Django中上传的文件,而无需数据库

时间:2020-06-21 12:37:32

标签: python python-3.x django django-forms django-views

我正在尝试保存文件并对HTML文件中的内容进行处理,我没有使用Django表单,但是我将Django用于后端,并且我不需要数据库,因为我不想保留任何文件。我尝试了django文档的指示。

html文件

 <input type="file" id="face_files" name="face_files" multiple >

view.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')

Inputform.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.

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

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

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