第一种直接读取文件返回响应
from django. http import StreamingHttpResponse
def read_file ( file_name, chunk_size= 512 ) :
with open ( file_name, "rb" ) as f:
while True :
c = f. read( chunk_size)
if c:
yield c
else :
break
def test ( request) :
file_path = ""
file_name = ""
response = StreamingHttpResponse( read_file( file_path) )
response[ "Content-Type" ] = "application/octet-stream"
response[ "Content-Disposition" ] = 'attachment; filename={0}' . format ( file_name)
response[ "Access-Control-Expose-Headers" ] = "Content-Disposition"
return response
第二种生成文件的时候返回,比如excel或者docx,这样不需要本地生成文件
sio = BytesIO( )
doc. save( sio)
sio. seek( 0 )
response = HttpResponse( content_type= "application/octet-stream" )
response[ "Content-Disposition" ] = 'attachment; filename={0}' . format ( file_name)
response[ "Access-Control-Expose-Headers" ] = "Content-Disposition"
response[ "Access-Control-Expose-Headers" ] = "Content-Disposition"
response. write( sio. getvalue( ) )
return response