亲宝软件园·资讯

展开

Django学习之文件上传与下载

人气:0


文件上传

1.新建django项目,创建应用stu: python manage.py startapp stu

2.在配置文件setting.py INSTALLED_APP 中添加新创建的应用stu

3.配置urls,分别在test\urls 和子路由stu\urls 中

#test\urls
urlpatterns = [
 url(r'^admin/', admin.site.urls),
 url(r'^student/',include('stu.urls'))
]

#stu\urls
from django.conf.urls import url
import views

urlpatterns=[
 url(r'^$',views.index_view)
]

4.创建视图文件index_view.py

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','')
 import os
 if not os.path.exists('media'): #判断是否存在文件media,不存在则创建一个
  os.makedirs('media')
 with open(os.path.join(os.getcwd(),'media',photo.name),'wb') as fw: #以读的方式打开目录为/media/photo.name 的文件 别名为fw
  fw.write(photo.read()) #读取photo文件并将其写入(一次性读取完)
       for chunk in fw.chunks:
    fw.write(chunk)
 return HttpResponse('注册成功')
 else:
 return HttpResponse('页面跑丢了,稍后再试!')

5.创建模板文件

<!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>
 <lable>姓名:<input type="text" name ='uname'></lable>
 </p>
 <p>
 <lable>头像:<input type="file" name ='photo'></lable>
 </p>
 <p>
 <lable><input type="submit" value="注册"></lable>
 </p>
</form>
</body>
</html>

文件存在数据库中并查询所有信息

1.创建模型类

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

# Create your models here.
from django.db import models
class Student(models.Model):
 sid = models.AutoField(primary_key=True)
 sname = models.CharField(max_length=30)
 photo = models.ImageField(upload_to='img')
 class Meta:
 db_table='t_stu'

 def __unicode__(self):
 return u'Student:%s' %self.sname

2.修改配置文件setting.py 添加新内容

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

3.通过创建的模型类 来映射数据库表

python mange.py makemigrations stu

python mange.py migrate

4.添加新的子路由地址

urlpatterns=[
 url(r'^$',views.index_view),
   url(r'^upload/$',views.upload_view),
 url(r'^show/$',views.showall_view)
]

5.在views文件中添加新的函数 showall_view()

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()
 return render(request,'show.html',{'stus':stus})

6.创建模板 显示查询到所有的信息

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<table border="1" width="500px" cellspacing="0">
 <tr>
 <th>编号</th>
 <th>姓名</th>
 <th>图片</th>
 <th>操作</th>
 </tr>
 <tr>
 {% for stu in stus %}
  <td>{{ forloop.counter }}</td>
  <td>{{ stu.sname }}</td>
  <td><img src="{{ MEDIA_URL}}{{ stu.photo }}"/> </td>
  <td><a href="#" rel="external nofollow" >操作</a></td>
 {% endfor %}
 </tr>
</table>
</body>
</html>

7.配置根路由 test\urls.py 读取后台上传的文件

from django.views.static import serve

if DEBUG:
 urlpatterns+=url(r'^media/(?P<path>.*)/$', serve, {"document_root": MEDIA_ROOT}),

8.再次修改配置文件setting.py  在TEMPLATE中添加新的内容 可以获取到media中的内容

'django.template.context_processors.media'

9.访问127.0.0.1:8000/student/ 上传学生信息

访问127.0.0.1:8000/student/show/ 查看所有学生的信息

文件的下载

1.配置子路由 访问views.py 下的download_view()函数

urlpatterns=[
 url(r'^$',views.index_view),
 url(r'^upload/$',views.upload_view),
 url(r'^show/$',views.showall_view),
 url(r'^download/$',views.download_view)
]
import os
def download_view(request):
 #获取文件存放的位置
 filepath = request.GET.get('photo','')
 print filepath
 #获取文件的名字
 filename = filepath[filepath.rindex('/')+1:]
 print filename
 path = os.path.join(os.getcwd(),'media',filepath.replace('/','\\'))
 with open(path,'rb') as fr:
 response = HttpResponse(fr.read())
 response['Content-Type'] = 'image/png'
 # 预览模式
 response['Content-Disposition'] = 'inline;filename=' + filename
 # 附件模式
 response['Content-Disposition']='attachment;filename='+filename
 return response

2.修改show.html 文件中下载栏的超链接地址

<tr>
 {% for stu in stus %}
  <td>{{ forloop.counter }}</td>
  <td>{{ stu.sname }}</td>
  <td><img src="{{ MEDIA_URL}}{{ stu.photo }}"/> </td>
  <td><a href="/student/download/?photo={{ stu.photo }}" rel="external nofollow" >下载</a></td>
 {% endfor %}
</tr>

3.访问127.0.0.1:8000/studnet/show/ 查看学生信息

点击操作栏中的下载 即可将学生照片下载到本地

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论