目標:利用django實現上傳文件功能
1,先設置路由系統
urls.py
from django.conf.urls import url,include from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^upload/$', views.upload), ]
2,配置html模板文件(前端頁面展示)
templates/upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload/" method="post" enctype="multipart/form-data"> <p><input type="file" name="f1"></p> <p><input type="text" name="hostname"></p> <input type="submit" value="upload"> </form> </body> </html>
3,開始寫上傳邏輯
views.py
#_*_ coding:utf-8 -*-
from django.shortcuts import render,HttpResponse
from django.views.generic.list import ListView
def index(request):
return HttpResponse("haha")
def upload(request):
if request.method == "POST": #判斷接收的值是否為POST
inp_files = request.FILES #上傳文件的接收方式應該是request.FILES
file_obj = inp_files.get('f1') #通過get方法獲取upload.html頁面提交過來的文件
f = open(file_obj.name,'wb') #將客戶端上傳的文件保存在服務器上,一定要用wb二進制方式寫入,否則文件會亂碼
for line in file_obj.chunks(): #通過chunks分片上傳存儲在服務器內存中,以64k為一組,循環寫入到服務器中
f.write(line)
f.close()
return render(request,'upload.html') #將處理好的結果通過render方式傳給upload.html進行渲染
4,上傳功能全部完成,比較簡單,我們來進行驗證
上傳本地一個png的圖片,然后點擊upload提交
點擊提交后,在服務器上看到了剛剛上傳的文件“django流程圖”
通過Django實現分片上傳文件成功。