uploadfile.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>头像上传</title>
</head>
<body>
<form action="{% url 'app:uploadfile' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="headimg">
<input type="submit" value="上传">
</form>
</body>
</html>
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/img')
views.py
import time
from django.shortcuts import render
from Django_demo import settings
def uploadfile(request):
if request.method == 'POST':
headimg = request.FILES.get('headimg')
filename = str(int(time.time())) + '-' + headimg.name
filepath = os.path.join(settings.MEDIA_ROOT, filename)
with open(filepath, 'wb') as f:
for foo in headimg.chunks():
f.write(foo)
return