django中实现上传文件
作者:互联网
django中实现上传文件
- 配置文件(settings.py)
- 在工程目录下创建一个static目录
- static目录下创建一个upfile目录保存上传文件
//settings.py中添加内容
STATIC_URL = '/static/'
# 上传文件目录
MDEIA_ROOT = os.path.join(BASE_DIR, 'static/upfile')
- 创建模板(upfile.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/savefile" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
- 视图
import os
from django.conf import settings
def upfile(request):
return render(request, 'upfile.html')
def savefile(request):
if request.method == 'POST':
f = request.FILES['file']
# 文件在服务器端的路径
filePath = os.path.join(settings.MDEIA_ROOT, f.name)
with open(filePath, 'wb') as fp:
for info in f.chunks():
fp.write(info)
return HttpResponse('上传成功')
else:
return HttpResponse('上传失败')
- 配置url
url(r'^upfile$', view.upfile),
标签:文件,return,settings,request,django,static,上传,upfile 来源: https://blog.csdn.net/robot_code/article/details/93763442