文件下载
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中使用了缓存,更加节省资源。

浙公网安备 33010602011771号