国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Django基于客戶端下載文件實現方法

瀏覽:81日期:2024-10-10 13:30:11

方法一: 使用HttpResonse

下面方法從url獲取file_path, 打開文件,讀取文件,然后通過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)

然而該方法有個問題,如果文件是個二進制文件,HttpResponse輸出的將會是亂碼。對于一些二進制文件(圖片,pdf),我們更希望其直接作為附件下載。當文件下載到本機后,用戶就可以用自己喜歡的程序(如Adobe)打開閱讀文件了。這時我們可以對上述方法做出如下改進, 給response設置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有個很大的弊端,其工作原理是先讀取文件,載入內存,然后再輸出。如果下載文件很大,該方法會占用很多內存。對于下載大文件,Django更推薦StreamingHttpResponse和FileResponse方法,這兩個方法將下載文件分批(Chunks)寫入用戶本地磁盤,先不將它們載入服務器內存。

方法二: 使用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的子類,是小編我推薦的文件下載方法。如果我們給file_response_download加上@login_required裝飾器,那么我們就可以實現用戶需要先登錄才能下載某些文件的功能了。

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Django
相關文章:
主站蜘蛛池模板: 牡丹江市| 五大连池市| 财经| 长乐市| 玉环县| 蕲春县| 扶风县| 蕲春县| 隆子县| 班玛县| 从化市| 宜章县| 嘉峪关市| 龙岩市| 堆龙德庆县| 汝阳县| 辽宁省| 诏安县| 新野县| 那坡县| 鲜城| 丽江市| 枝江市| 伊金霍洛旗| 赤峰市| 内乡县| 饶平县| 浦东新区| 崇礼县| 荥阳市| 古蔺县| 集安市| 洛阳市| 龙口市| 新沂市| 农安县| 虞城县| 凯里市| 东源县| 内丘县| 蒙城县|