views视图代码:
import os
from datetime import datetime
from django.shortcuts import render
from day09 import settings
def upload(request):
return render(request,'app/fileupload.html')
# 文件上传处理
def doupload(request):
# 获取上传文件
file = request.FILES.get('picture')
print(type(file))
print(file.name,file.size)
# 文件存储的目标路径
# path = os.path.join(settings.MDEIA_ROOT,file.name)
# 日期目录
myDate = datetime.today().strftime("%Y/%m/%d")
path = os.path.join(settings.MDEIA_ROOT,myDate)
# 判定目录是否存在,如果不存在则创建
if not os.path.exists(path):
os.makedirs(path) #可以递归创建子目录
# 文件的绝对路径
path = os.path.join(path,file.name)
with open(path,'wb') as fp:
# 如果文件大于2.5M,分片读写
if file.multiple_chunks():
for chip in file.chunks():
fp.write(chip)
else:
fp.write(file.read())
return HttpResponse("文件上传")
settings中代码:
在设置中上传文件的路径:
#上传文件存放的目录
MDEIA_ROOT = os.path.join(BASE_DIR,'static/upload')
templates模板:
form表单中必须设置enctype="multipart/form-data"属性。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="{% url 'app:doupload' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
头像:<input type="file" name="picture"> <input type="submit" value="上传">
</form>
</body>
</html>
如果你想要把存入数据库中的头像取出加载到界面时要注意,数据库中存的是个相对路径,你要进行一下拼接:
datas['icon'] = '/static/uploadfiles/' + user.icon.url
print(user.icon.url)
print(user.icon)