- 首先需要在ima的setting文件夹设置一个目录,用于存放上传之后的的文件
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\','/')
MEDIA_URL = '/media/'
url.py中添加如下行
path('upload', views.upload),
views.py中添加如下
def upload(request):
if request.method == 'GET':
return render(request,'upload.html')
elif request.method == 'POST':
obj = request.FILES.get('genelist')
#两种路径的写法均可,路径应该可以自己定义为服务器路径
# f = open(os.path.join('E:/IMA/web/imasite/ima/media/',obj.name),'wb')
f=open(os.path.join('media',obj.name),'wb')
for line in obj.chunks():
f.write(line)
f.close()
return HttpResponse('上传成功')
- 在文件夹下添加一个html模板,模板内容如下
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传页面</title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="genelist" />
<input type="submit" value="上传" />
</form>
</body>
</html>