第一步:用户上传页面设计
# 路径:Templats/index.html
<body>
<form action="/home/upload/" method="post" enctype="multipart/form-data">
# 跨域请求操作需要使用模板语言,在setting文件TEMPLATES中注册Templats为模板文件夹
# 'DIRS': [os.path.join(BASE_DIR, 'Templats/')],
{% csrf_token %}
<input type="file" name="img">
<input type="submit" value="上传">
</form>
</body>
第二步:主文件夹中路由设计
# 路径:Tmail/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from home import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/$', views.index),
url(r'^home/', include('home.urls_home'))
]
第三步:子文件夹中路由设计
# 路径:/home/urls_home.py
from django.conf.urls import url
from home import views
urlpatterns = [
url(r'upload/$', views.UploadFile.post),
]
第四步:试图文件设计
# 路径:/home/views.py
from django.conf import settings
from django.shortcuts import render
from django.utils.datetime_safe import datetime
from django.views import View
def index(request):
return render(request, 'index.html')
class UploadFile(View):
def post(request):
if request.method == 'POST':
upload_file = request.FILES.get('img')
file_name_last = upload_file.name.split('.').pop()
file_name = 'IMG_{}.{}'.format(datetime.now().strftime('%Y%M%d%H%M%S'), file_name_last)
with open(settings.MEDIA_ROOT + '/img/' + file_name, 'wb') as file:
for chunk in upload_file.chunks():
file.write(chunk)
return render(request, 'success.html')
注释:
from django.views import view
class UploadFile(view):
'''
前端 表单必须是post请求 ENCTPE=multipart/form-data
imput type='file'
如果发现request. FILES如果是空 检查是否是post请求
'''
def post(request):
# request.FILES 是一个字典
# 文件名称
# 文件内容
# content-type 文件的类型
upload_file = request.FILE.get('img')
'''
# read()
读取文件上传的数据,慎用,一次性读取
# mutiple_chunks(size)
判断文件是否足够大
# chunks(size)
返回一个生成器对象,把上传的文件切割,可以定制size
# name
获取文件名称
# size 获取文件的大小
# content_type 上传文件的类型
# charset 文件的编码
'''
'''
客户上传文件
服务器端保存文件 二进制数据
保存文件的路径到数据
'''
'''
对客户端上传文件服务器重命名,防止同名文件覆盖
对路径进行细分 | 对文件进行重命名(保证名字是唯一的)
1 获取文件的后缀名 os.path.splittext() str()
IMG_ 年月日时分秒
str.split()
str.slice()
'''
# xxx.jpg xxx.pdf IMG_20180428123945.jpg
file_name_last = upload_file.name.split('.').pop()
# file_name = 'IMG_' + datetime. + file_name_last
file_name = 'IMG_{}.{}'.format(datetime.now().strftime('%Y%M%d%H%M%S'),file_name_last)
# 123.jpg xx.pdf
with open(settings.MEDIA_ROOT + '/img/' + file_name, 'wb') as file:
# 把二进制的数据保存到服务器
for chunk in upload_file.chunks():
file.write(chunk)
return render(request,'success.html')
第五步:测试,操作成功返回success网页
# 路径:Templats/success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>success!!</h3>
</body>
</html>
补充:配置setting文件
# 注册模板
'DIRS': [os.path.join(BASE_DIR, 'Templats/')],
# 注册静态文件
STATIC_URL = '/static/'
STATIC_URL = os.path.join(BASE_DIR, 'static/')
# 注册媒体文件
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')