Django中request.FILES及文件和处理器的异常行为

0 投票
1 回答
621 浏览
提问于 2025-04-18 18:37

我有一个需求,需要同时上传两个文件。request对象的FILES属性看起来是这样的:

<MultiValueDict: {u'output': [<InMemoryUploadedFile: output.txt (text/plain)>], u'history': [<InMemoryUploadedFile: .history.json (application/octet-stream)>]}>

我把这两个文件存储为变量:

output = request.FILES['output']
history = request.FILES['history']

然后,我把这两个文件分别分配给Django模型中的两个文件字段,想要保存它们,但只有分配给output的文件字段能正确保存,另一个应该包含历史内容的字段却没有任何内容。

在调试这个问题时,我发现我只能读取history的内容一次,之后history.read()返回的是空字符串:''。而output可以读取很多次,每次都能返回outputs的实际内容。

我尝试了很多不同的方法来保存history的内容,包括使用FileContentFile创建新文件,但似乎Django一直不让我成功创建一个能在.read()时返回这个内容的文件。

值得一提的是,history包含很多看起来像二进制的数据,这些数据是有效的JSON格式,大小大约是12k。file显示它是:

ASCII text, with very long lines, with no line terminators

我是不是在Django处理history的方式上遗漏了什么?

补充:这是我尝试保存的模型字段(不过我觉得问题发生在保存之前):

   history_file = models.FileField(
        upload_to=history_file_name,
        null=True,
        blank=True
    )
    output_file = models.FileField(
        upload_to=output_file_name,
        null=True,
        blank=True
    )

这是保存模型的代码:

    result.output_file = output
    challenge.history_file = history
    challenge.save()

这个问题发生在一个基于视图的CBV的post方法中。我没有更改Django 1.6.5自带的任何默认文件处理设置。

1 个回答

0

我现在还不太明白为什么会出现这个问题,但我通过以下方法解决了这个问题:

history = files['history']
history_content = history.read()
from django.core.files.base import ContentFile
history_content_file = ContentFile(history_content)
challenge.history_file.save(NAME, history_content_file)

顺便说一下,history_content_file 这个文件只能读取一次。

希望这能帮助到其他人,如果我以后搞明白了发生了什么,我会再分享更多信息。

撰写回答