項(xiàng)目整體目錄結(jié)構(gòu)
- 在settings中配置STATICFILES_DIRS
STATIC_URL = '/static/'
# 設(shè)置靜態(tài)文件存放的物理目錄
STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')]
2.在settings中配置MEDIA_ROOT
# 設(shè)置文件上傳路徑
MEDIA_ROOT = os.path.join(BASE_DIR,'static/media')
3.在TEMPLATES中創(chuàng)建上傳文件頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳文件</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="/upload">
{% csrf_token %}
<input type="file" name="myFile"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
注意:form標(biāo)簽的屬性中添加 enctype="multipart/form-data" ,否則后臺獲取file為空
4.在url中配置處理函數(shù)的路徑
from django.conf.urls import url
from django.contrib import admin
from django.urls import path
from bookstore import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^show',views.show),
url(r'^upload',views.upload_handle)
]
5.在views中處理上傳邏輯:
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render,redirect
def show(request):
if request.method =="GET":
return render(request,'upload.html')
def upload_handle(request):
"""
處理上傳圖片
:param request:
:return:
"""
# 1.獲取上傳的文件
file = request.FILES.get('myFile')
# 創(chuàng)建一個(gè)文件
save_path = '%s/%s'%(settings.MEDIA_ROOT,file.name)
# 2.獲取上傳文件內(nèi)容并寫入到創(chuàng)建的文件中
with open(save_path,'wb') as f:
for content in file.chunks():
f.write(content)
# 寫入到數(shù)據(jù)庫保存上傳記錄
# 返回
return HttpResponse("上傳成功")
測試效果 http://127.0.0.1:8000/show