繁体   English   中英

在没有django表单的情况下以django处理HTML格式的上传文件

[英]Handling uploaded files in HTML form in django WITHOUT django forms

问题是我有一个动态生成的HTML表单,因此我不知道会有多少文件/文本输入。 因此,我决定不使用表单,而是通过request.FILES处理文件上传。

到目前为止,这是我的代码。

elif request.method == "POST":
        for ta in text_attachments:
            ta.text = request.POST["text-" + ta.id.__str__()]
            ta.save()
        for fa in text_attachments:
            if request.FILES.get("file-" + fa.id.__str__(), None):
                # fa.file = request.FILES["file-" + fa.id.__str__()]
                handle_uploaded_file(fa, request.FILES["file-" + fa.id.__str__()])
                fa.save()

这是handle_uploaded_file函数:

def handle_uploaded_file(instance, f):
    path = coopertaion_attachment_path(instance, f.name)
    with open(path, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

这是决定文件上传位置的功能。

def coopertaion_attachment_path(instance, filename):
    print("Filename: " + filename)
    os.umask(0)
    path = 'applications/cooperation/%s/' % instance.application.user.id
    att_path = os.path.join(settings.MEDIA_ROOT, path)
    if settings.DEFAULT_FILE_STORAGE == "django.core.files.storage.FileSystemStorage":
        if not os.path.exists(att_path):
            os.makedirs(att_path, 0o777)
            print("Creating path...")

    return os.path.join(path, filename)

最后,我总是得到这个错误:

[Errno 2] No such file or directory: 'applications/cooperation/1/filename.pdf'

没有django格式,甚至可以处理上传的文件吗? 如何将上载的文件分配给我的模型之一的FileField

您似乎做对了(文件上传和处理)。 问题出在您的cooperation_attachment_path方法中。 您将返回os.path.join(path, filename) ,其中path相对于您的项目路径不存在,因此会出现错误。

[Errno 2]没有这样的文件或目录:'applications / cooperation / 1 / filename.pdf'

att_path拥有绝对路径,因此您应该执行以下操作:

return os.path.join(att_path, filename)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM