前言
django开发页面上的文件上传功能
模型
models.py 设计数据模型,upload_to参数是指定文件上传的路径
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
class Upfile(models.Model):
"""上传文件"""
file = models.FileField(upload_to="upload")
title = models.CharField(max_length=30)
timestamp = models.DateTimeField(auto_now_add=True)
在setting中添加2个参数,文件上传到项目的media目录
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
视图功能
post提交数据的时候,通过request.FILES
获取文件参数
from .models import Upfile
from django.views import View
from django import forms
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
class UpFileModelForm(forms.ModelForm):
"""上传文件"""
class Meta:
model = Upfile
fields = ["file", "title"]
class UpFileModelView(View):
def get(self, request):
form_obj = UpFileModelForm()
return render(request, "upfile.html", locals())
def post(self, request):
form_obj = UpFileModelForm(request.POST, request.FILES)
if form_obj.is_valid():
f = form_obj.save()
msg = "保存成功"
return JsonResponse({"code": 0, "msg": "success", "data": "/media/"+str(f.file)})
else:
msg = "参数不合法"
return render(request, "upfile.html", locals())
模板
form表单需设置enctype="multipart/form-data"
属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<body>
<form action="" method="POST" id="detail-form" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form_obj %}
<p>
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
</p>
{% endfor %}
<p>
{% if msg %}
{{ msg }}
{% endif %}
</p>
<p>
<input type="submit" value="提交" >
</p>
</form>
</body>
</body>
</html>
urls.py设置访问地址
from django.conf.urls import url
from django.views.static import serve
from . import settings
urlpatterns = [
url('^upimage$', views.UpFileModelView.as_view()),
url(r'^media/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}),
]
实现效果
访问页面
选择文件上传
上传成功返回
复制返回的图片地址,拼接请求可以访问上传的图片http://localhost:8000/media/upload/21_fyErshM.png