博客信息

Python Django 视图层(上传下载)

发布时间:『 2019-08-17 04:44』  博客类别:Python  阅读(658)

原生上传

 

主路由

from django.conf.urls import url, include
from django.contrib import admin

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


子路由

from django.conf.urls import url
import views

urlpatterns = {
    url(r'^$', views.index_view),
}


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')
    else:
        uname = request.POST.get('uname', '')
        photo = request.FILES.get('photo', '')
        import os
        if not os.path.exists('static'):
            os.makedirs('static')

        with open(os.path.join(os.getcwd(), 'static', photo.name), 'wb') as fw:
            # 一次性读取文件
            # fw.write(photo.read())
            # 分块读取
            for chunk in photo.chunks():
                fw.write(chunk)

        return HttpResponse('上传成功!')


- photo.read():从文件中读取整个上传的数据,这个方法只适合小文件;

 

- photo.chunks():按块返回文件,通过在for循环中进行迭代,可以将大文件按块写入到服务器中;

 

- photo.multiple_chunks():这个方法根据myFile的大小,返回True或者False,当myFile文件大于2.5M(默认为2.5M,可以调整)时,该方法返回True,否则返回False,因此可以根据该方法来选择选用read方法读取还是采用chunks方法

 

- photo.name:这是一个属性,不是方法,该属性得到上传的文件名,包括后缀,如123.exe

 

- photo.size:这也是一个属性,该属性得到上传文件的大小。


小李飞刀_Python


被上传的2.png图片


小李飞刀_Python


图片就这样上传到了项目的static文件夹下了

 

Django上传

 

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.FileField(upload_to='imgs')

    class Meta:
        db_table = 't_stu'

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


然后在终端用命令生成表

 

Settings.py

INSTALLED_APPS = [
    ...
    'student'
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}



# 数据库中保留的请求图片的地址
MEDIA_URL = '/media/'
# 文件真实存放位置
MEDIA_ROOT = os.path.join(BASE_DIR,'media')


Student/urls.py

urlpatterns = {
    url(r'^$', views.index_view),
    url(r'^django_upload/$', views.django_upload),
    url(r'^showall/$', views.showall_view),
}

 

填写学生信息的页面

http://127.0.0.1:8000/student/

提交学生信息处理的路由地址

http://127.0.0.1:8000/student/django_upload/


小李飞刀_Python


小李飞刀_Python


默认是不会展示图片的


小李飞刀_Python

 

需要配置

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'  # 配置这句话
            ],
        },
    },
]

 

然后可看到下列效果

小李飞刀_Python

下载

 

Student/urls.py

from django.conf.urls import url
import views

urlpatterns = {
    url(r'^$', views.index_view),
    url(r'^django_upload/$', views.django_upload),
    url(r'^showall/$', views.showall_view),
    url(r'^download/$', views.download_view),
}

 

Student/views.py

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

import os

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
# 整个下载
from student.models import Student


def index_view(request):
    if (request.method == 'GET'):
        return render(request, 'index.html')
    else:
        uname = request.POST.get('uname', '')
        photo = request.FILES.get('photo', '')
        import os
        if not os.path.exists('static'):
            os.makedirs('static')

        with open(os.path.join(os.getcwd(), 'static', photo.name), 'wb') as fw:
            # 一次性读取文件
            # fw.write(photo.read())
            # 分块读取
            for chunk in photo.chunks():
                fw.write(chunk)

        return HttpResponse('上传成功!')


# django文件上传
def django_upload(request):
    # 1.获取请求参数
    sname = request.POST.get('sname')
    photo = request.FILES.get('photo')

    # 2.插入数据库
    stu = Student.objects.create(sname=sname, photo=photo)

    # 3.判断是否注册成功
    if stu:
        return HttpResponse('注册成功!')

    return HttpResponseRedirect('/student/')


def showall_view(request):
    # 查询所有学生信息
    stus = Student.objects.all()

    return render(request, 'show.html', {'stus': stus})


def download_view(request):
    # 获取文件存放位置
    filepath = request.GET.get('photo', '')
    # 获取文件名
    filename = filepath[filepath.rindex('/') + 1:]

    # 获取文件绝对路径
    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

 

文件中文名处理

from django.utils.encoding import escape_uri_path

response['Content-Disposition']="attachment;filename*=utf-8''{}".format(escape_uri_path(file_name))


前端页面

index.html 

show.html 


下载页面预览图

小李飞刀_Python


over......


关键字:     Python       Django       上传下载  

备案号:湘ICP备19000029号

Copyright © 2018-2019 javaxl晓码阁 版权所有