Django基于客戶(hù)端下載文件實(shí)現(xiàn)方法
方法一: 使用HttpResonse
下面方法從url獲取file_path, 打開(kāi)文件,讀取文件,然后通過(guò)HttpResponse方法輸出。
import osfrom django.http import HttpResponsedef file_download(request, file_path): # do something... with open(file_path) as f: c = f.read() return HttpResponse(c)
然而該方法有個(gè)問(wèn)題,如果文件是個(gè)二進(jìn)制文件,HttpResponse輸出的將會(huì)是亂碼。對(duì)于一些二進(jìn)制文件(圖片,pdf),我們更希望其直接作為附件下載。當(dāng)文件下載到本機(jī)后,用戶(hù)就可以用自己喜歡的程序(如Adobe)打開(kāi)閱讀文件了。這時(shí)我們可以對(duì)上述方法做出如下改進(jìn), 給response設(shè)置content_type和Content_Disposition。
import osfrom django.http import HttpResponse, Http404def 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有個(gè)很大的弊端,其工作原理是先讀取文件,載入內(nèi)存,然后再輸出。如果下載文件很大,該方法會(huì)占用很多內(nèi)存。對(duì)于下載大文件,Django更推薦StreamingHttpResponse和FileResponse方法,這兩個(gè)方法將下載文件分批(Chunks)寫(xiě)入用戶(hù)本地磁盤(pán),先不將它們載入服務(wù)器內(nèi)存。
方法二: 使用SteamingHttpResonse
import osfrom django.http import HttpResponse, Http404, StreamingHttpResponsedef 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的子類(lèi),是小編我推薦的文件下載方法。如果我們給file_response_download加上@login_required裝飾器,那么我們就可以實(shí)現(xiàn)用戶(hù)需要先登錄才能下載某些文件的功能了。
import osfrom django.http import HttpResponse, Http404, FileResponsedef 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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. docker鏡像完全卸載的操作步驟2. IntelliJ IDEA導(dǎo)入jar包的方法3. 使用Maven 搭建 Spring MVC 本地部署Tomcat的詳細(xì)教程4. IntelliJ IDEA配置Tomcat服務(wù)器的方法5. idea刪除項(xiàng)目的操作方法6. IntelliJ IDEA設(shè)置自動(dòng)提示功能快捷鍵的方法7. IntelliJ IDEA安裝插件的方法步驟8. IntelliJ IDEA調(diào)整字體大小的方法9. idea打開(kāi)多個(gè)窗口的操作方法10. idea導(dǎo)入maven項(xiàng)目的方法

網(wǎng)公網(wǎng)安備