文件上傳原理是無論上傳的文件格式是什么,將文件以二進制的數據格式讀取並寫入網站指定的文件里。
在myApp下配置urls.py路由:
#myApp urls.py from argparse import Namespace from operator import index from django.urls import path,re_path,include from . import views from django.views.generic import RedirectView urlpatterns = [ path("",views.index,name="index"), path("download/file1",views.download1,name="download1"), path("download/file2",views.download2,name="download2"), path("download/file3",views.download3,name="download3"), path("upload",views.upload,name="uploaded") ] #配置全局404頁面 handler404 = "myApp.views.page_not_found" #配置全局500頁面 handler500 = "myApp.views.page_error"
在myApp應用的視圖中,實現文件上傳的功能:
from django.shortcuts import render from django.http import HttpResponse import os # Create your views here. def index(request): # return redirect("index:shop",permanent=True) return render(request,"index.html") def upload(request): #請求方法為POST時,執行文件上傳 print("debug ++++++++++++++++++++++++") print(request.method) if request.method == "POST": #獲取上傳的文件,如果沒有文件,就默認為None myFile = request.FILES.get("myfile",None) if not myFile: return HttpResponse("no files for upload") #打開特定的文件進行二進制的寫操作 f = open(os.path.join("E:\myDjango\\file",myFile.name),"wb+") #分塊寫入文件 for chunk in myFile.chunks(): f.write(chunk) f.close() return HttpResponse("upload over!") else: #請求方法為get時,生成文件上傳頁面 return render(request,"index.html")
- 瀏覽器將用戶上傳的文件讀取后,通過http的post請求將二進制數據傳到django,當django收到post請求后,從請求對象的屬性FILES獲取文件信息,然后再D盤的upload文件夾里創建新的文件,文件名(從文件信息對象myFile.name屬性獲取),與用戶上傳的文件名相同。
- 從文件信息對象myFile.chunks()讀取文件內容,並寫入D盤的upload文件夾的文件中。
- myFile.name 獲取上傳文件的文件名,包含文件后綴名。
- myFile.size 獲取上傳文件的文件大小。
- myFile.content_type 獲取文件類型,通過后綴名判斷文件類型。
- myFile.read() 從文件對象里讀取整個文件上傳的數據,這個方法只適合小文件。
- myFile.chunks() 按流式響應方式讀取文件,在for循環中進行迭代,將大文件分塊寫入服務器所指定的保存位置。
- myFile.multiple_chunks() 判斷文件對象的文件大小,返回True或者False,當文件大於2.5MB時,該方法返回True,否則返回False,因此,可以根據該方法來選擇選用read()方法讀取還是采用chunks()方法讀取
在index.html中,添加上傳文件的控件:
<html> <header> <title>首頁文件處理</title> </header> <body> <a href="{%url 'myApp:download1' %}">下載1</a> <a href="{%url 'myApp:download2' %}">下載2</a> <a href="{%url 'myApp:download3' %}">下載3</a> <form enctype="multipart/form-data" action="/upload" method="post"> <!-- django 的csrf 防御機制 --> {%csrf_token%} <input type="file" name="myfile" /> <br> <input type="submit" value="上傳文件" /> </form> </body> </html>
在模板文件index.html使用form標簽的文件控件file生成文件上傳功能,該控件將用戶上傳的文件以二進制的形式讀取,讀取方式由form標簽的屬性entype=“multipart/form-data”設置