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

Django下载的Zip文件损坏无法打开,请求排查响应代码问题

Django下载Zip文件损坏问题的解决

问题根源

你怀疑的这段响应代码确实存在问题:

  • FileResponse设计用来接收类文件对象,但你用f.read()把整个Zip文件的字节内容读入内存后传给它,这会导致响应流处理异常,最终下载到本地的文件损坏。
  • 构造Content-Disposition时使用了转义的",这会让浏览器解析文件名时出现不必要的干扰。

修正后的响应代码

with open(zip_file_path, 'rb') as f:
    response = FileResponse(f, content_type='application/zip')
    response['Content-Disposition'] = f'attachment; filename="note{note.id}.zip"'

额外优化建议

  1. 避免硬编码文件路径:用settings.MEDIA_ROOT拼接路径,适配不同部署环境
from django.conf import settings
import os

# 确保目标目录存在
download_dir = os.path.join(settings.MEDIA_ROOT, 'downloaded_notes')
os.makedirs(download_dir, exist_ok=True)

file_path = os.path.join(download_dir, f'note{note.id}.txt')
zip_file_path = os.path.join(download_dir, f'note{note.id}.zip')
  1. 可靠获取附件路径:直接使用NoteFile的file.path属性,代替从URL截取的方式
for note_file in notefiles:
    zipf.write(note_file.file.path, os.path.basename(note_file.file.name))
  1. 清理临时文件:下载完成后删除生成的txt和zip文件,避免占用磁盘空间
# 在return response之前添加
os.remove(file_path)
os.remove(zip_file_path)

内容的提问来源于stack exchange,提问作者keyboardNoob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:25:53