Django 實現下載文件功能

jopen 9年前發布 | 64K 次閱讀 Django Web框架

本文首載于Gevin的博客

基于Django建立的網站,如果提供文件下載功能,最簡單的方式莫過于將靜態文件交給Nginx等處理,但有些時候,由于網站本身邏輯,需要通過Django提供下載功能,如頁面數據導出功能(下載動態生成的文件)、先檢查用戶權限再下載文件等。因此,有必要研究一下文件下載功能在Django中的實現。

最簡單的文件下載功能的實現

將文件流放入HttpResponse對象即可,如:

def file_download(request):
    # do something...
    with open('file_name.txt') as f:
        c = f.read()
    return HttpResponse(c)

這種方式簡單粗暴,適合小文件的下載,但如果這個文件非常大,這種方式會占用大量的內存,甚至導致服務器崩潰

更合理的文件下載功能

Django的HttpResponse對象允許將迭代器作為傳入參數,將上面代碼中的傳入參數c換成一個迭代器,便可以將上述下載功能優化為對大小文件均適合;而Django更進一步,推薦使用StreamingHttpResponse對象取代HttpResponse對象,StreamingHttpResponse對象用于將文件流發送給瀏覽器,與HttpResponse對象非常相似,對于文件下載功能,使用StreamingHttpResponse對象更合理。

因此,更加合理的文件下載功能,應該先寫一個迭代器,用于處理文件,然后將這個迭代器作為參數傳遞給StreaminghttpResponse對象,如:

from django.http import StreamingHttpResponse

def big_file_download(request):
    # do something...

    def file_iterator(file_name, chunk_size=512):
        with open(file_name) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    the_file_name = "file_name.txt"
    response = StreamingHttpResponse(file_iterator(the_file_name))

    return response

文件下載功能再次優化

上述的代碼,已經完成了將服務器上的文件,通過文件流傳輸到瀏覽器,但文件流通常會以亂碼形式顯示到瀏覽器中,而非下載到硬盤上,因此,還要在做點優化,讓文件流寫入硬盤。優化很簡單,給StreamingHttpResponse對象的Content-Type和Content-Disposition字段賦下面的值即可,如:

response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="test.pdf"'

完整代碼如下:

from django.http import StreamingHttpResponse

def big_file_download(request):
    # do something...

    def file_iterator(file_name, chunk_size=512):
        with open(file_name) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    the_file_name = "big_file.pdf"
    response = StreamingHttpResponse(file_iterator(the_file_name))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)

    return response
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!