Django实现文件上传下载功能

yipeiwu_com6年前Python基础

项目介绍

最近学习django,通过文件上传下载这个小项目,总结下常用的知识点。
做这个案例我有以下需求:

1.要支持一次上传多个文件

2.支持上传后记录上传的数据以及列表展示

3.支持下载和删除文件记录

效果展示

数据库记录

开发步骤

创建项目:

django-admin startproject file_upload
cd file_upload
python manage.py startapp uploader

目录结构:

0.settings.py

LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False

1.urls.py

父:

from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
 path('admin/', admin.site.urls),
 path('uploader/', include('uploader.urls'))
]

子:

from django.contrib import admin
from django.urls import path, include
from . import views
 
app_name = 'uploader'
 
urlpatterns = [
 path('', views.upload, name='upload'), # 上传
 path('list/', views.list), # 列表
 path('download/<id>', views.download, name='download'), # 下载
 path('delete/<id>', views.delete, name='delete'), # 删除
]

2.models.py

from django.db import models
from django.utils import timezone
 
'''
文件记录
'''
class FileInfo(models.Model):
 file_name = models.CharField(max_length=500)
 file_size = models.DecimalField(max_digits=10, decimal_places=0)
 file_path = models.CharField(max_length=500)
 upload_time = models.DateTimeField(default=timezone.now())

3.forms.py

from django import forms
 
'''
上传表单
'''
class UploadForm(forms.Form):
 file = forms.FileField(
 widget=forms.ClearableFileInput(attrs={'multiple': True}), # 支持多文件上传
 label='选择文件...',
 help_text='最大100M'
 )

4.views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.http import HttpResponseRedirect
from django.http import FileResponse
from django.template import RequestContext
from django.urls import reverse
from django.utils.http import urlquote
 
from .models import FileInfo
from .forms import UploadForm
import os
 
 
# 上传文件
def upload(request):
 # Handle file upload
 if request.method == 'POST':
 form = UploadForm(request.POST, request.FILES)
 if form.is_valid():
  files = request.FILES.getlist('file')
  for f in files:
  file_info = FileInfo(file_name=f.name, file_size=1 if 0 < f.size < 1024 else f.size / 1024, file_path=os.path.join('D:\\upload', f.name))
  file_info.save()
  # 上传
  destination = open(os.path.join("D:\\upload", f.name), 'wb+')
  for chunk in f.chunks():
   destination.write(chunk)
  destination.close()
 
  # 返回上传页
  return HttpResponseRedirect('/uploader/list')
 else:
 form = UploadForm() # A empty, unbound form
 return render(request, 'uploader/upload.html', {'form': form})
 
 
# 文件列表
def list(request):
 file_infos = FileInfo.objects.all()
 
 return render(request, 'uploader/list.html', {'file_infos': file_infos})
 
 
# 下载文件
def download(request, id):
 file_info = FileInfo.objects.get(id=id)
 print('下载的文件名:' + file_info.file_name)
 file = open(file_info.file_path, 'rb')
 response = FileResponse(file)
 response['Content-Disposition'] = 'attachment;filename="%s"' % urlquote(file_info.file_name)
 return response
 
 
# 删除文件
def delete(request, id):
 file_info = FileInfo.objects.get(id=id)
 file_info.delete()
 file_infos = FileInfo.objects.all()
 
 return HttpResponseRedirect('/uploader/list')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

操作Windows注册表的简单的Python程序制作教程

通过Python操作注册表有两种方式,第一种是通过Python的内置模块 _winreg;另一种方式就是Win32 Extension For Python 的win32api模块,但是...

Python的对象传递与Copy函数使用详解

1、对象引用的传值或者传引用 Python中的对象赋值实际上是简单的对象引用。也就是说,当你创建一个对象,然后把它赋值给另一个变量的时候,Python并没有拷贝这个对象,而是拷贝了这个对...

python scipy卷积运算的实现方法

python scipy卷积运算的实现方法

scipy的signal模块经常用于信号处理,卷积、傅里叶变换、各种滤波、差值算法等。 *两个一维信号卷积 >>> import numpy as np >...

Python数据类型详解(三)元祖:tuple

一.基本数据类型   整数:int   字符串:str(注:\t等于一个tab键)   布尔值: bool   列表:list   列表用[]   元祖:tuple   元祖用()...

python3.6.3安装图文教程 TensorFlow安装配置方法

python3.6.3安装图文教程 TensorFlow安装配置方法

本文主要介绍Python3.6及TensorFlow的安装和配置流程。 一、Python官网下载自己电脑和系统对应的Python安装包。  网址:下载地址 一直往下拉到Fil...