# 上傳圖片
* 當Django在處理文件上傳的時候,文件數據被保存在request.FILES
* FILES中的每個鍵為<input type="file" name="" />中的name
* 注意:FILES只有在請求的方法為post且提交的<form>帶有enctype="multipart/form-data"的情況下才會包含數據。否則,FILES將為一個空的類似于字典的對象
* 使用模型處理上傳文件:將屬性定義成models.ImageFiled累心
```text
class UploadFile(models.Model):
picture = models.ImageField(upload_to='upfile/')
```
* 注意:如果屬性類型為ImageField需要安裝包Pilow
```text
pip insatll pillow
```
* 圖片存儲路徑
* 在static目錄下創建upfile文件夾
* 圖片上傳后,會保存到"/static/upfile"文件夾
* 打開settings.py文件,增加media\_root項
```text
# 上傳文件目錄
MDETA_ROOT = os.path.join(BASE_DIR,r'static/upfile')
```
* 使用django后臺管理,遇到imageField類型的屬性會出現一個file框,完成文件上傳
```text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="{% url 'myapp:savefile' %}" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file"/><br />
<input type="submit" value="submit"/>
</form>
</body>
</html>
```
配置路由:
```text
from django.conf.urls import url,include
from . import views
app_name = 'myapp'
urlpatterns = [
url(r'^index/$',views.index),
url(r'^upfile/$',views.upfile,name="upfile"),
url(r'^savefile/$',views.savefile,name='savefile'),
]
```
配置視圖
```text
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def upfile(request):
return render(request,'upfile.html')
import os
from test4.settings import *
def savefile(request):
if request.method == 'POST':
f = request.FILES['file']
# 合成文件在服務器端的路徑
# 1
filePath = os.path.join(MDETA_ROOT,f.name)
# 2
` # filePath = os.path.join(MDETA_ROOT+"/image",f.name)
with open(filePath,'wb') as fp:
for info in f.chunks():
fp.write(info)
return HttpResponse("上傳成功")
```