運行效果
# 創(chuàng)建Download項目 django-admin startproject Download # 創(chuàng)建down_app app python manage.py startapp down_app
Download/Download/settings.py
1.添加注冊APP:down_app
2.設(shè)置模板文件路徑:templates
3、編寫視圖函數(shù):views.py
Download/down_app/views.py
import os from django.http import HttpResponse from django.http import StreamingHttpResponse def image_down(request): """ 下載圖片 """ img_name = request.GET.get("username") + ".png" # 二維碼圖片名 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 項目根目錄 file_path = os.path.join(base_dir, 'antirisk/CodeGenerate/image/code', img_name) # 二維碼的絕對路徑 if not os.path.isfile(file_path): # 判斷下載文件是否存在 return HttpResponse("Sorry but Not Found the File") def file_iterator(file_path, chunk_size=512): """ 文件生成器,防止文件過大,導(dǎo)致內(nèi)存溢出 :param file_path: 文件絕對路徑 :param chunk_size: 塊大小 :return: 生成器 """ with open(file_path, mode='rb') as f: while True: c = f.read(chunk_size) if c: yield c else: break try: # 設(shè)置響應(yīng)頭 # StreamingHttpResponse將文件內(nèi)容進行流式傳輸,數(shù)據(jù)量大可以用這個方法 response = StreamingHttpResponse(file_iterator(file_path)) # 以流的形式下載文件,這樣可以實現(xiàn)任意格式的文件下載 response['Content-Type'] = 'application/octet-stream' # Content-Disposition就是當(dāng)用戶想把請求所得的內(nèi)容存為一個文件的時候提供一個默認(rèn)的文件名 response['Content-Disposition'] = f'attachment;filename="1.png"' # 文件名不可設(shè)置為中文 except: return HttpResponse("Sorry but Not Found the File") return response
4、修改路由配置:urls.py
Download/Download/urls.py
from django.contrib import admin from django.urls import path, re_path from down_app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index), re_path('download/)', views.image_down, name="download"), ]
5、創(chuàng)建并編寫:index.html
Download/templates/index.html
!DOCTYPE html> html lang="en"> head> meta charset="UTF-8"> title>Title/title> /head> body> a href="/download/" rel="external nofollow" >下載圖片/a> /body> /html>
運行
# 運行項目 python manage.py runserver
# 訪問: http://127.0.0.1:8000/
到此這篇關(guān)于Python Django搭建文件下載服務(wù)器的實現(xiàn)的文章就介紹到這了,更多相關(guān)Django搭建文件下載服務(wù)器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:喀什 欽州 景德鎮(zhèn) 黃山 臺灣 三沙 濟南 宿遷
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python Django搭建文件下載服務(wù)器的實現(xiàn)》,本文關(guān)鍵詞 Python,Django,搭建,文件下載,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。