3 ways to achieve django file downloads


方法一:使用HttpResponse
from django.shortcuts import HttpResponse def file_down(request): file=open('/home/amarsoft/download/example.tar.gz','rb') response =HttpResponse(file) response['Content-Type']='application/octet-stream' response['Content-Disposition']='attachment;filename="example.tar.gz"' return response 方法二:使用StreamingHttpResponse from django.http import StreamingHttpResponse def file_down(request): file=open('/home/amarsoft/download/example.tar.gz','rb') response =StreamingHttpResponse(file) response['Content-Type']='application/octet-stream' response['Content-Disposition']='attachment;filename="example.tar.gz"' return response 方法三:使用FileResponse from django.http import FileResponse def file_down(request): file=open('/home/amarsoft/download/example.tar.gz','rb') response =FileResponse(file) response['Content-Type']='application/octet-stream' response['Content-Disposition']='attachment;filename="example.tar.gz"' return response

Summary: Comparison Although the use of these three methods can achieve, but recommended FileResponse, use the cache FileResponse, the more economical resource. Although it is three ways, but the same principle, it means one way.

Guess you like

Origin www.cnblogs.com/lvye001/p/11586413.html