关于Django文件上传和下载的Demo

Django文件上传与下载实战
本文详细介绍了使用Django框架进行文件上传和下载的全过程,包括配置settings文件、创建模型、视图处理、模板展示及下载逻辑实现。

文件上传下载折磨了我一下午,是非常难受了。

接下来是操作过程:

startapp新建好应用文件后,把一些配置做好。

1、配置settings文件。

(1)、TEMPLATES里添加一行语句。

 (2)、在settings文件里添加MEDIA_URL,MEDIA_ROOT两个参数,绿字是自己定义的。

2、根路由urls.py文件里添加新路径和映射路径代码,便于之后图片的显示。

3、app目录下新建一个urls.py文件

#coding=utf-8

from django.conf.urls import url

from stu import views

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

4、app目录下views.py文件编写代码

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

# Create your views here.
from stu.models import Student

def index_views(request):
    #请求方式是GET就跳转到register.html页面
    if request.method == 'GET':
        return render(request,'register.html')

5、templates目录下新建register.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#跳转到/student/,post方式提交#}
{#enctype就是encodetype就是编码类型的意思。#}
{#multipart/form-data是指表单数据有多部分构成,既有文本数据,又有文件等二进制数据的意思#}
<form action="/student/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <label>姓名:</label><input type="text" name="sname">
    <label>头像:</label><input type="file" name="sfi">
    <input type="submit" value="提交">
</form>
</body>
</html>

6、models.py文件编写并在终端映射数据库表

from django.db import models

# Create your models here.
class Student(models.Model):
    sid = models.AutoField(primary_key=True)
    sname = models.CharField(max_length=30)
    sfi = models.ImageField(upload_to='imgs')

7、继续到app目录下完善views.py文件代码

def index_views(request):
    if request.method == 'GET':
        return render(request,'register.html')
    else:
        #从前端页面获取数据并存到数据库和本地文件中
        sname =request.POST.get('sname')
        sfi = request.FILES.get('sfi')
        Student.objects.create(sname=sname,sfi=sfi)
        stu = Student.objects.all()
        #成功后跳转到展示页面,并把数据传输过去
        return render(request,'show.html',{'stu':stu})

8、templates目录下新建show.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/student/" method="get">
    <table cellspacing="0" border="1">
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>图片</th>
            <th>操作</th>
        </tr>
        {% for foo in stu %}
            <tr>
                <th>{{ forloop.counter }}</th>
                <th>{{ foo.sname }}</th>
                {# {{ MEDIA_URL }}可以在settings文件中修改#}
                <th><img width="150px" src="{{ MEDIA_URL }}{{ foo.sfi }}"/></th>
                <th><a href="/student/download/?sfi={{ foo.sfi }}">下载</a></th>
        </tr>
        {% endfor %}

    </table>
</form>
</body>
</html>

9、继续完成下载逻辑

(1)、先添加路径

(2)、views.py完成download_views函数

def download_views(request):
    sfi = request.GET.get('sfi','')
    filename = sfi[sfi.rindex('/')+1:]
    import os
    #获取源地址
    path = os.path.join(os.getcwd(),'media',sfi)
    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

10、最后调试截图

(1)、上传页面

(2)、展示页面

(3)、点击下载后 

发现用Chrome时灵时不灵,有时候会弹出下载框,有时候弹不出来,用IE就不会这样,要是有哪位大佬知道是咋回事拜托留个言哈!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值