Django基於客戶端下載檔案實現方法
阿新 • • 發佈:2020-04-21
方法一: 使用HttpResonse
下面方法從url獲取file_path,開啟檔案,讀取檔案,然後通過HttpResponse方法輸出。
import os from django.http import HttpResponse def file_download(request,file_path): # do something... with open(file_path) as f: c = f.read() return HttpResponse(c)
然而該方法有個問題,如果檔案是個二進位制檔案,HttpResponse輸出的將會是亂碼。對於一些二進位制檔案(圖片,pdf),我們更希望其直接作為附件下載。當檔案下載到本機後,使用者就可以用自己喜歡的程式(如Adobe)開啟閱讀檔案了。這時我們可以對上述方法做出如下改進, 給response設定content_type和Content_Disposition。
import os from django.http import HttpResponse,Http404 def media_file_download(request,file_path): with open(file_path,'rb') as f: try: response = HttpResponse(f) response['content_type'] = "application/octet-stream" response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) return response except Exception: raise Http404
HttpResponse有個很大的弊端,其工作原理是先讀取檔案,載入記憶體,然後再輸出。如果下載檔案很大,該方法會佔用很多記憶體。對於下載大檔案,Django更推薦StreamingHttpResponse和FileResponse方法,這兩個方法將下載檔案分批(Chunks)寫入使用者本地磁碟,先不將它們載入伺服器記憶體。
方法二: 使用SteamingHttpResonse
import os from django.http import HttpResponse,Http404,StreamingHttpResponse def stream_http_download(request,file_path): try: response = StreamingHttpResponse(open(file_path,'rb')) response['content_type'] = "application/octet-stream" response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) return response except Exception: raise Http404
方法三: 使用FileResonse
FileResponse方法是SteamingHttpResponse的子類,是小編我推薦的檔案下載方法。如果我們給file_response_download加上@login_required裝飾器,那麼我們就可以實現使用者需要先登入才能下載某些檔案的功能了。
import os from django.http import HttpResponse,FileResponse def file_response_download1(request,file_path): try: response = FileResponse(open(file_path,'rb')) response['content_type'] = "application/octet-stream" response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) return response except Exception: raise Http404
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。