到目前為止,我們的注意力都在HTML網頁上,但是實際上,在網站上除了HTML外還有圖片,文件,PDF等等。
首先來看下返回一張圖片為例,讀取本地磁盤上的一張圖片並返回到網頁上顯示。
def test1(request):
image_data=open(r'd:/django_test2/code.JPG','rb').read()
return HttpResponse(image_data,content_type='image/JPG')
在網頁上可以看到我們的代碼截圖顯示在瀏覽器上
接下來看下如何生成文件,在網站上經常要下載后台的文件或者是顯示后台文件的內容。
下面通過HttpResponse的方法可以直接將讀取的內容顯示在網頁上
def test1(request):
with open(r'd:/django_test2/django.txt') as f:
c=f.read()
return HttpResponse(c)
但是這種方法只適合小文件,如果遇到大的文件則會很耗內存。
Django中提供了StreamingHttpResponse可以以流的方式進行下載。代碼如下。
from django.http import StreamingHttpResponse
def test1(request):
def file_itertor(file_name,chunk_size=512):
with open(file_name) as f:
while True:
c=f.read(chunk_size)
if c:
yield c
else:
break
file_name=r'd:/django_test2/django.txt'
download_file='django.txt'
response=StreamingHttpResponse(file_itertor(file_name))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(download_file)
return response
如果沒有設置Content-Type和Content-Disposition,那么文件流會直接顯示在瀏覽器上,如果要下載到硬盤上則必須設置Content-Type和Content-Disposition。其中download_file為下載的時候顯示的文件名。
刷新網頁的時候,會自動下載該文件
最后來看下PDF文檔的生成。
首先要安裝一個reportlab。pip install reportlab
生成代碼如下:
def test1(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="django-pdf.pdf"'
p = canvas.Canvas(response)
p.drawString(50, 50, "Hello django.")
p.showPage()
p.save()
return response
刷新在瀏覽器中自動下載生成的PDF文件
生成的pdf文件內容。