Python Django接口返回zip文件下载后提示压缩包无效如何解决
问题根因
- 读取zip文件时使用了文本模式而非二进制模式:zip是二进制格式文件,使用
r文本模式读取并指定编码时,Python会自动对内容做文本转义、换行符转换处理,直接破坏原始二进制结构,导致输出的压缩包损坏。 - 错误使用DRF的
Response类返回二进制内容:DRF的Response默认会对传入内容做JSON序列化适配,会把原始二进制流转为字符串格式,二次破坏压缩包结构。
修复代码
替换文件读取模式为二进制rb,使用Django原生HttpResponse返回二进制流即可:
from django.http import HttpResponse from rest_framework.views import APIView def get_response(): # 二进制模式读取文件,无需指定编码 with open('zip_file_path.zip', 'rb') as f: file_data = f.read() response = HttpResponse(file_data, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="ReportTest.zip"' return response class GenerateZIP(APIView): def post(self, request): return get_response()
如果需要返回大体积zip文件,推荐使用流式响应减少内存占用:
from django.http import StreamingHttpResponse from rest_framework.views import APIView def file_iterator(file_path, chunk_size=8192): with open(file_path, 'rb') as f: while chunk := f.read(chunk_size): yield chunk def get_response(): response = StreamingHttpResponse( file_iterator('zip_file_path.zip'), content_type='application/zip' ) response['Content-Disposition'] = 'attachment; filename="ReportTest.zip"' return response class GenerateZIP(APIView): def post(self, request): return get_response()
内容的提问来源于stack exchange,提问作者Aroosh Rana
相关产品推荐
相关产品推荐

