Python的Django实现文件上传、下载
Django实现文件上传
1. 配置setting文件
1.1. 在setting里面配置文件上传路径,在setting末尾添加
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR,'static')
1.2. 在项目根目录新建static文件夹
1.3. 配置TEMPLATES,添加如下内容
'django.template.context_processors.static'
添加完如下所示
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.static'
], }, }, ]
2. 配置父路由urls
. 配置通过数据加载加载图片
from django.views.static import serve from .settings import MEDIA_ROOT, DEBUG if DEBUG: urlpatterns += url(r'^media/(?P<path>.*)/$', serve, {'document_root': MEDIA_ROOT}),
3. 配置子路由urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^index/', views.index),
url(r'^login/', views.login),
url(r'^reg/', views.reg),
url(r'^files/', views.file),
url(r'^download/', views.download_view),
]
4. 构建模型数据库类models
from django.db import models
# 用户表
class userinfo(models.Model):
user_name =models.CharField(max_length=32,primary_key=True)
user_pwd=models.CharField(max_length=32)
def __str__(self):
return self.user_name
#上传文件表
class files(models.Model):
files_id=models.AutoField(primary_key=True)
files_name=models.FileField(upload_to='media')
files_user=models.ForeignKey(userinfo,on_delete=models.CASCADE)
# Create your models here.
5.视图逻辑处理views
import os
from django.http import HttpResponse
from app01 import models
from django.shortcuts import render, redirect
def index(request):
username = request.session.get("username")
tip = "请选择要上传的文件!"
if request.method=="POST":
#上传文件
myFile = request.FILES.get("file", None) # 获取上传的文件,如果没有文件,则默认为None
tip="上传文件成功!"
models.files.objects.create(files_name=myFile,files_user_id=username)
return render(request, "index.html", {"tip": tip, "username": username})
return render(request,"index.html",{"tip":tip,"username":username})
# 查看所有上传文件
def file(request):
files_data=models.files.objects.all()
return render(request,"file_list.html",{"files":files_data})
# 下载文件
def download_view(request):
photo = request.GET.get('photo', '')
file = open("static/"+photo, 'rb')
response = HttpResponse(file)
response['Content-Type'] = 'application/octet-stream' # 设置头信息,告诉浏览器这是个文件
response['Content-Disposition'] = 'attachment;filename='+photo[6:]
return response
# Create your views here.
6.前端页面
6.1. index.html
<body style="background-color: #F7F7F7;">
<lable>你好!{{ username }}</lable>
<form action="" enctype="multipart/form-data" method="post">
<div id="header" style="margin: 40px auto;text-align: center;font-size: 36px;">
<label>文件上传系统</label>
</div>
<div id="body" style="width: 800px;height: 600px;background-color: white;margin: 60px auto;">
<div id="body1" style="display: flex; justify-content: space-around;position: relative;top: 40px;">
<input style="display: block; width: 300px;" class="btn btn-info" type="file" name="file" id="file" value="" />
<button style="display: block; width: 300px;" class="btn btn-info" type="submit">上传文件</button>
</div>
<div style="font-size: 18px;position: relative;top: 120px;left: 55px;" id="">
<label>{{ tip }}</label>
</div>
</div>
</form>
</body>
6.2. file_list.html
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li class="active"><a href="/product_list/" class="one-pan-link-mark">上传列表</a></li>
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h2 class="sub-header">上传文件列表</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>主键</th>
<th>上传文件名称</th>
<th>上传账号</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for file in files %}
<tr>
<td>{{ file.pk }}</td>
<td>{{ file.files_name }}</td>
<td>{{ file.files_user.user_name }}</td>
<td><a href="/download/?photo={{ file.files_name }}">下载</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
源码已上传码云进行开源欢迎下载学习使用:
https://gitee.com/wuhuhahaha/filedemo

浙公网安备 33010602011771号