文件上传
def upload(request):
if request.method == 'POST':
# photo 是表单中文件上传的name
file = request.FILES.get('photo')
print(file)
# 文件路径
path = os.path.join(settings.MEDIA_ROOT,file.name)
#文件类型过滤
ext = os.path.splitext(file.name)
if len(ext) < 1 or not ext[1] in settings.ALLOWED_FILEEXTS:
return redirect(reverse('upload'))
#解决文件重名
if os.path.exists(path):
#日期目录
dir = datetime.today().strftime("%Y/%m/%d")
dir = os.path.join(settings.MEDIA_ROOT,dir)
if not os.path.exists(dir):
os.makedirs(dir) #递归创建目录
#list.png
file_name = ext[0] + datetime.today().strftime("%Y%m%d%H%M%S") + str(randint(1,1000))+ ext[1] if len(ext)>1 else ''
path = os.path.join(dir,file_name)
print(path)
# 创建新文件
with open(path,'wb') as fp:
# 如果文件超过2.5M,则分块读写
if file.multiple_chunks():
for block1 in file.chunks():
fp.write(block1)
else:
fp.write(file.read())
return redirect(reverse('index'))
return render(request,'upload.html')
-
html
<form action="/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} 头像: <input type="file" name="photo"> <br> 允许上传:png,jpeg,jpg,gif,bmp文件 <br> <input type="submit" value="上传"> </form>