django-admin startproject studenttest python manage.py startapp student打开 student/views.py 文件,创建 uploadimage() 视图函数
def uploadimage(request):
return render(request,"student/file.html")
打开
student/urls.py
文件,配置
url(注意这个最后面的,要记得添加,养成良好习惯)
url(r"^file/$",views.uploadimage),在 templates/student/ 目录下创建模板 file.html 。在模板中定义上传表单
表单内容
④打开 student/views.py 文件,创建 handle() 视图函数,用于接收表单保存图片。 request 对象的 FILES 属性用 于接收请求的文件,包括图片内容。
| request.FILES.get(name) | 通过 标签的 name 属性值获得图片对象。 |
| 对象 .chunks() | 返回图片对象的数据值,类型为生成器对象。若要获取所有数据内容,则需要进行 遍历处理。 |
| 对象 .name | 返回图片对象的文件名。 |
| 对象 .file | 获取的二进制数据 |
from django.conf import settings
from django.http import HttpResponse
from .models import PictrueInfo
def handle(request):
image = request.FILES.get("image")
# 图片名
image_name = image.name
# 图片内容
image_content = image.chunks()
# 写入文件
path = "%s/student/%s"%(settings.MEDIA_ROOT,image_name)
with open(path,"wb") as fs:
for temp in image_content:
fs.write(temp)
# 图片路径名写入数据库
PictrueInfo.objects.create(picture="student/%s"%image_name)
return HttpResponse("OK")
打开 student/urls.py
文件,配置
url
url(r"^handleimage/$",views.handle),
运行服务器,在浏览器中(注:当选择文件后点击按钮上传图片即可)输入如下网址:
http://127.0.0.1:8000/file/
当然127.0.0.1也可以换成localhost
可在pycharm中的项目中检查图片是否上传成功 media>>student
接下来是在网页中显示图片,打开 student/views.py 文件,创建 showpic()视图函数
# 批量显示图片
def showpic(request):
picturelist = PictrueInfo.objects.all()
return render(request,"student/picture.html",{"picturelist":picturelist})
需要提醒的是,每操作完一个视图函数,都需要修改相应的url配置
打开
student/urls.py
文件,配置
url
url(r"^show/$",views.showpic),在 templates/student/ 目录下创建模板 picture.html
批量显示图片
{% for picture in picturelist %}
{ picture.picture }}" width="200px" height="150px">
{% endfor %}
运行服务器,点击编译器控制台中的如下网址http://127.0.0.1:8000,登陆后添加/show/,
即http://127.0.0.1:8000/show/
即可查看刚刚上传的图片一起显示了。
以上就是Django框架的一个小应用,有兴趣的朋友可以自行操作。



