Django文件上传下载
1. 项目目录结构
2. 创建模板目录并配置 settings.py: D:\Users\file_up_and_down_demo\file_up_and_down_demo\settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'index', ]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'index/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',
],
},
},
]
3. 创建文件模型,并映射到数据库
以默认的 sqlite 为例,在 index App 下的 models.py 中自定义一个代表文件的模型
该模型包含 3 个字段:
- 文件名称
- 文件保存路径
- 上传时间
D:\Users\file_up_and_down_demo\index\models.py
from django.db import models # index App models.py from django.db import models from django.utils import timezone # Create your models here. # 文件模型 class FileModel(models.Model): # 文件名称 name = models.CharField(max_length=50) # 文件保存路径 path = models.CharField(max_length=100) # 上传时间 upload_time = models.DateTimeField(default=timezone.now)
然后,在项目根目录下执行下面 2 条命令,将模型结构映射到数据库中
# 数据库映射
Python3 manage.py makemigrations
python3 manage.py migrate
4.自定义表单控件
在内部自定义一个表单类,继承于 forms.Form
from django import forms class FileForm(forms.Form): file = forms.FileField( # 支持多文件上传 widget=forms.ClearableFileInput(attrs={'multiple': True}), label='请选择文件', )
5. 添加上传、下载路由 URL
为上传、下载功能添加路由 URL
D:\Users\file_up_and_down_demo\file_up_and_down_demo\urls.py
# 项目urls.py
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')) ]
# index App urls.py
from django.urls import path from .views import * urlpatterns = [ # 上传 path('', index_view, name='index'), # 下载 path('download/<id>', download_view, name='download') ]
6. 编写模板文件
D:\Users\file_up_and_down_demo\index\templates\upload.html
其中
- form 代表视图函数传过来的表单实体对象
- form.as_p 代表以字段格式渲染所有的表单元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>主页-上传文件</title> </head> <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="确定上传"> </form> </body> </html>
7. 上传视图函数
D:\Users\file_up_and_down_demo\index\views.py
from django.shortcuts import render from index.models import FileModel from index.forms import FileForm from django.http import HttpResponse, FileResponse from django.utils.encoding import escape_uri_path import os import urlquote # Create your views here. def index_view(request): """ 上传文件 :param request: :return: """ if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): # 选择的文件 files = request.FILES.getlist('file') # 遍历写入到数据库中 for file in files: # 写入到数据库中 file_model = FileModel(name=file.name, path=os.path.join('./upload', file.name)) file_model.save() # 写入到服务器本地 destination = open(os.path.join("./upload", file.name), 'wb+') for chunk in file.chunks(): destination.write(chunk) destination.close() # 提示上传成功 return HttpResponse('上传成功!') else: form = FileForm() return render(request, 'upload.html', locals()) # 下载视图函数 def download_view(request, id): """ 下载文件 :param request: :param id:文件id :return: """ file_result = FileModel.objects.filter(id=id) # 如果文件存在,就下载文件 if file_result: file = list(file_result)[0] # 文件名称及路径 name = file.name path = file.path # 读取文件 file = open(path, 'rb') response = FileResponse(file) # 使用urlquote对文件名称进行编码 response['Content_type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="%s"' % escape_uri_path(name) return response else: return HttpResponse('文件不存在!')
需要提前在项目根目录创建一个 upload 文件夹,用于存放上传的文件
8. 运行并测试
下载
用一个例子来演示会更加清晰