对于文本类型的文件,在传输过程中往往会发生一点点意想不到的效果。
为了保证文件的完整性,我推荐对于Excel等类型的文本文件使用HttpResponse进行传送
filename = 'xxxxxxx.xlsx'
with open(file_path, 'rb') as f:
f_byte = f.read()
response = HttpResponse(f_byte)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename)
return response
from django.http import FileResponse
with open(file_path, 'rb') as f:
f_byte = f.read()
response = FileResponse(f_byte)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename)
return response
from django.http import StreamingHttpResponse
def file_iterator(file_path, chunk_size=512):
with open(file_path, 'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
response = StreamingHttpResponse(file_iterator(file_path))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename)
return response