文件上傳必須為POST提交方式。
表達’<form>’中文件上傳時必須帶有enctype=”multipart/formdata”時才會包含文件內容數據。
表單中用<input type=”file” name=”xxx”>標簽上傳文件
例:
(a)views.py
# 文件上傳
def test_upload(request):
if request.method == 'GET':
return render(request, 'test_upload.html')
elif request.method == 'POST':
return HttpResponse('上傳成功')
(b)urls.py’
urlpatterns = [
path('admin/', admin.site.urls),
path('test_upload', views.test_upload),
]
(c)templates/test_upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳文件</title>
</head>
<body>
<form action="/test_upload" method="post" enctype="multipart/form-data">
<p>
<input type="text" name="title">
</p>
<p>
<input type="file" name="myfile">
</p>
<p>
<input type="submit" value="上傳">
</p>
</form>
</body>
</html>
訪問:http://192.168.28.128:8000/test_upload
(a)視圖
視圖函數中,用request.FILES取文件框的內容
file = request.FILES[‘XXX’]
注:
(b)配置文件
配置文件的訪問路徑和存儲路徑:在setting.py中設置MEDIA相關配置;Django把用戶上傳的文件統稱為media資源。
# file:settings.py
MEDIA_URL = ‘/media/’
MEDIA_ROOT = os.path.join(BASE_DIR, ‘media’)
(c)路由
MEDIA_URL和MEDIA_ROOT需手動綁定
在主路中添加路由:
from djang.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
注:等價於做了MEDIA_URL開頭的路由,Django接到該特征請求後去MEDIA_ROOT路徑查找資源。
(d)文件寫入
(方法一):傳統open方式
def upload_view(request):
if request.method == 'GET':
return render(request, 'test_upload.html')
elif request.method == 'POST':
a_file = request.FILES['myfile']
print('上傳文件名是:', a_file.name)
filename = os.path.join(settings.MEDIA_ROOT, a_file.name)
with open(filename, 'wb') as f:
data = a_file.file.read()
f.write(data)
return HttpResponse('接收文件:' + a_file.name + '成功')
(方法二):借助ORM
字段:FileField(upload=’子目錄名’)
例:
(a)views.py
@csrf_exempt
def test_upload(request):
if request.method == 'GET':
return render(request, 'test_upload.html')
elif request.method == 'POST':
title = request.POST['title']
myfile = request.FILES['myfile']
Content.objects.create(title=title, picture=myfile)
return HttpResponse('--上傳文件成功--')
(b)templas/test_upload.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳文件</title>
</head>
<body>
<form action="/test_upload" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>
<input type="text" name="title">
</p>
<p>
<input type="file" name="myfile">
</p>
<p>
<input type="submit" value="上傳">
</p>
</form>
</body>
</html>
訪問:http://192.168.28.128:8000/test_upload
在項目的目錄中會保存該圖片
數據庫中:
浏覽器訪問:http://192.168.28.128:8000/media/picture/photo.jpeg