【问题标题】:Save file uploaded in Django without a database在没有数据库的情况下保存在 Django 中上传的文件
【发布时间】:2020-06-21 12:37:32
【问题描述】:

我正在尝试保存一个文件并从 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.

我做错了什么?

【问题讨论】:

  • 你能分享下你的观点吗?
  • 你能多粘贴一点你的文件吗?
  • @IainShelvington 我用views.py和InputForm编辑了这个问题。
  • @BrankoRadojevic 我的文件是.jpg,第一行二进制如下:b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x02\x01\x01\x01\x01\x01\x02\x01\x01\x01\x02\x02\x02\x02\x02\x04\x03\x02\x02\x02\x02\x05\x04\x04\x03\x04\x06\x05\x06\x06\x06\x05\x06\x06\x06\x07\t\x08\x06\x07\t\x07\x06\x06\x08\x0b\x08\t\n'
  • @Moe 当我 sadi "files" 我提到 Django 文件时:)

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-12-16
    • 2018-09-04
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    相关资源
    最近更新 更多