python基礎web之tornao文件的上傳與下載
django 文件的下載
- StreamingHttpResponse對象用於將文件流發送給浏覽器
- Content-Type和Content-Disposition字段賦值
def downloadFile(req):
'''
請參考本人19年寫的博客
https://blog.csdn.net/a6864657/article/details/88897178
'''
file_path = ''
filename = ''
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'] = f'attachment;filename="{filename}"'
return response