原生上传图片方式
#新建工程 python manage.py startapp test30 #修改 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stu' ] #修改urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'student/',include('stu.urls')), ] #新增加 stu/urls.py #coding:utf-8 from django.conf.urls import url import views urlpatterns = [ url(r'^$',views.index_view) ] #编辑 stu/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render # Create your views here. #原生上传文件方式 def index_view(request): if request.method == 'GET': return render(request,'index.html') elif request.method == 'POST': #获取请求参数 uname = request.POST.get('uname','') photo = request.FILES.get('photo','') print photo.name import os print os.getcwd() if not os.path.exists('media'): os.mkdir('media') #拼接路径 with open(os.path.join(os.getcwd(),'media',photo.name),'wb') as fw: # photo.read() #一次性读取文件到内存 # fw.write(photo.read()) #分块读取,性能高 for ck in photo.chunks(): fw.write(ck) return HttpResponse('It is post request,上传成功') else: return HttpResponse('It is not post and get request!') #新增加模板文件 templates/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/student/" method="post" enctype="multipart/form-data"> {% csrf_token %} <p> <label for="ua">姓名: </label> <input type="text" name="uname" id="ua"/> </p> <p> <label for="ph">头像: </label> <input type="file" name="photo" id="ph"/> </p> <p>      <input type="submit" value="注册"/> </p> </form> </body> </html> #效果如下: 访问: http://127.0.0.1:8000/student/
Django 图片上传方式
需求: 效果: 访问 http://127.0.0.1:8000/student/ 通过注册将姓名、头像地址传入数据库中; 访问 http://127.0.0.1:8000/student/showall 将数据库信息通过表格形式展示 ###过程 #修改 settings.py ,templates 新增加 'django.template.context_processors.media' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media' ], }, }, ] 末尾增加: # global_settings #指定上传文件存储相对路径(读取文件) MEDIA_URL = '/media/' #指定上传文件存储绝对路径(存储文件) MEDIA_ROOT = os.path.join(BASE_DIR,'media') #创建数据库模型 stu/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Student(models.Model): sno = models.AutoField(primary_key=True) sname = models.CharField(max_length=30) photo = models.ImageField(upload_to='imgs') def __unicode__(self): return u'Student:%s'%self.sname #生成数据库迁移文件,查看数据库表结构 python makemigrations stu python migrate #修改 urls.py 因为显示问题,增加 DEBUG 内容 from django.conf.urls import url, include from django.contrib import admin from test30.settings import DEBUG, MEDIA_ROOT urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'student/',include('stu.urls')), ] from django.views.static import serve if DEBUG: urlpatterns+=url(r'^media/("document_root": MEDIA_ROOT}), #修改 urls, stu/urls.py #coding:utf-8 from django.conf.urls import url import views urlpatterns = [ url(r'^$',views.index_view), url(r'^upload/$',views.upload_view), url(r'^showall/$',views.showall_view) ] # 修改 stu/views.py #django 上传文件方式 def upload_view(request): uname = request.POST.get('uname','') photo = request.FILES.get('photo','') #入库操作 Student.objects.create(sname=uname,photo=photo) return HttpResponse('上传成功!') #显示图片 def showall_view(request): stus = Student.objects.all() print stus return render(request,'show.html',{'stus':stus}) # 修改 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/student/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} <p> <label for="ua">姓名: </label> <input type="text" name="uname" id="ua"/> </p> <p> <label for="ph">头像: </label> <input type="file" name="photo" id="ph"/> </p> <p>      <input type="submit" value="注册"/> </p> </form> </body> </html> # 增加模板文件 show.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table width="500px" border="1" cellspacing="0"> <tr> <th>编号</th> <th>姓名</th> <th>头像</th> <th>操作</th> </tr> {% for stu in stus %} <tr> <td>{{ forloop.counter }}</td> <td>{{ stu.sname }}</td> <td><img style="width: 200px;" src="/UploadFiles/2021-04-08/{{ MEDIA_URL }}{{ stu.photo }}">图片下载功能
### 需求 在显示页面点击下载实现图片的下载功能 过程: #修改 show.html ,加入 下载的超链接 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table width="500px" border="1" cellspacing="0"> <tr> <th>编号</th> <th>姓名</th> <th>头像</th> <th>操作</th> </tr> {% for stu in stus %} <tr> <td>{{ forloop.counter }}</td> <td>{{ stu.sname }}</td> <td><img style="width: 200px;" src="/UploadFiles/2021-04-08/{{ MEDIA_URL }}{{ stu.photo }}">以上就是Django 实现图片上传和下载功能的详细内容,更多关于Django 图片上传和下载的资料请关注其它相关文章!
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“Django 实现图片上传和下载功能”评论...
更新日志
2024年11月08日
2024年11月08日
- 雨林唱片《赏》新曲+精选集SACD版[ISO][2.3G]
- 罗大佑与OK男女合唱团.1995-再会吧!素兰【音乐工厂】【WAV+CUE】
- 草蜢.1993-宝贝对不起(国)【宝丽金】【WAV+CUE】
- 杨培安.2009-抒·情(EP)【擎天娱乐】【WAV+CUE】
- 周慧敏《EndlessDream》[WAV+CUE]
- 彭芳《纯色角3》2007[WAV+CUE]
- 江志丰2008-今生为你[豪记][WAV+CUE]
- 罗大佑1994《恋曲2000》音乐工厂[WAV+CUE][1G]
- 群星《一首歌一个故事》赵英俊某些作品重唱企划[FLAC分轨][1G]
- 群星《网易云英文歌曲播放量TOP100》[MP3][1G]
- 方大同.2024-梦想家TheDreamer【赋音乐】【FLAC分轨】
- 李慧珍.2007-爱死了【华谊兄弟】【WAV+CUE】
- 王大文.2019-国际太空站【环球】【FLAC分轨】
- 群星《2022超好听的十倍音质网络歌曲(163)》U盘音乐[WAV分轨][1.1G]
- 童丽《啼笑姻缘》头版限量编号24K金碟[低速原抓WAV+CUE][1.1G]