You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中doc对象read方法报ValueError: I/O operation on closed file如何解决

问题原因

Django 框架中 request.FILES 拿到的文件对象属于 UploadedFile 类型,它的 read() 方法执行完成后,文件流会自动关闭,且文件指针会移动到文件末尾。你的代码里先后两次调用了 doc.read():第一次是 print(doc.read()) 语句,第二次是附件挂载的 msg.attach(doc.name, doc.read(), doc.content_type) 语句,第二次调用时文件已经处于关闭状态,因此触发了 ValueError: I/O operation on closed file 报错。

解决方案

只需要读取一次文件内容,将内容存储到变量中,后续打印、挂载附件都复用这个变量即可,修改后的业务代码如下:

def send_comment_mail_notification(request, space, target_email):
    message = request.POST.get('description', '')
    subject = request.POST.get('subject', '')
    from_mail = space.email
    to = target_email
    msg = EmailMessage(subject, message, from_mail, [to],)
    doc = request.FILES['document']
    # 仅读取一次文件内容,存储到变量复用
    doc_content = doc.read()
    print(doc_content)
    msg.attach(doc.name, doc_content, doc.content_type)
    msg.content_subtype = "html"
    msg.send()

如果不需要打印文件内容,也可以直接删除print(doc.read())语句,同样可以解决问题。

内容的提问来源于stack exchange,提问作者Azeez Oluwasegun Akinsola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 05:36:03