文件下载

Django中有三种方法进行文件下载

使用HttpResponse

from django.shortcuts import HttpResponse  
def file_down(request):  
    file=open('/home/eric/Desktop/test.jpg','rb')  
    response =HttpResponse(file)  
    response['Content-Type']='application/octet-stream'  
    response['Content-Disposition']='attachment;filename="test.jpg"'  
    return response 

使用StreamingHttpResponse

from django.http import StreamingHttpResponse  
def file_down(request):  
    file=open('/home/eric/Desktop/test.jpg','rb')  
    response =StreamingHttpResponse(file)  
    response['Content-Type']='application/octet-stream'  
    response['Content-Disposition']='attachment;filename="test.jpg"'  
    return response  

使用FileResponse

from django.http import FileResponse  
def file_down(request):  
    file=open('/home/eric/Desktop/test.jpg','rb')  
    response =FileResponse(file)  
    response['Content-Type']='application/octet-stream'  
    response['Content-Disposition']='attachment;filename="test.jpg"'  
    return response 

在三种方法中推荐使用FileResponse,在FileResponse中使用了缓存,更加节省资源。

 

posted @ 2019-06-30 21:57  Jin同学  阅读(109)  评论(0)    收藏  举报