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"'
额外优化建议
- 避免硬编码文件路径:用
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')
- 可靠获取附件路径:直接使用
NoteFile的file.path属性,代替从URL截取的方式
for note_file in notefiles: zipf.write(note_file.file.path, os.path.basename(note_file.file.name))
- 清理临时文件:下载完成后删除生成的txt和zip文件,避免占用磁盘空间
# 在return response之前添加 os.remove(file_path) os.remove(zip_file_path)
内容的提问来源于stack exchange,提问作者keyboardNoob
相关产品推荐
相关产品推荐

