Django實(shí)現(xiàn)文件上傳下載功能
項(xiàng)目介紹
最近學(xué)習(xí)django,通過(guò)文件上傳下載這個(gè)小項(xiàng)目,總結(jié)下常用的知識(shí)點(diǎn)。
做這個(gè)案例我有以下需求:
1.要支持一次上傳多個(gè)文件
2.支持上傳后記錄上傳的數(shù)據(jù)以及列表展示
3.支持下載和刪除文件記錄
效果展示

數(shù)據(jù)庫(kù)記錄

開(kāi)發(fā)步驟
創(chuàng)建項(xiàng)目:
django-admin startproject file_upload cd file_upload python manage.py startapp uploader
目錄結(jié)構(gòu):

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()
# 返回上傳頁(yè)
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')
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用Python實(shí)現(xiàn)Shp格式向GeoJSON的轉(zhuǎn)換方法
JSON(JavaScript Object Nonation)是利用鍵值對(duì)+嵌套來(lái)表示數(shù)據(jù)的一種格式,以其輕量、易解析的優(yōu)點(diǎn),這篇文章主要介紹了利用Python實(shí)現(xiàn)Shp格式向GeoJSON的轉(zhuǎn)換,需要的朋友可以參考下2019-07-07
Python調(diào)用ChatGPT制作基于Tkinter的桌面時(shí)鐘
這篇文章主要為大家詳細(xì)介紹了Python如何調(diào)用ChatGPT制作基于Tkinter的桌面時(shí)鐘,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-03-03
Python標(biāo)準(zhǔn)庫(kù)筆記struct模塊的使用
這篇文章主要介紹了Python標(biāo)準(zhǔn)庫(kù)筆記struct模塊的使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-02-02
Centos7 Python3下安裝scrapy的詳細(xì)步驟
這篇文章主要介紹了Centos7 Python3下安裝scrapy的詳細(xì)步驟,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03
python通過(guò)floor函數(shù)舍棄小數(shù)位的方法
這篇文章主要介紹了python通過(guò)floor函數(shù)舍棄小數(shù)位的方法,實(shí)例分析了Python中floor函數(shù)的功能及使用技巧,需要的朋友可以參考下2015-03-03
淺談Python peewee 使用經(jīng)驗(yàn)
這篇文章主要介紹了淺談Python peewee 使用經(jīng)驗(yàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10
python字符串,元組,列表,字典互轉(zhuǎn)代碼實(shí)例詳解
這篇文章主要介紹了python字符串,元組,列表,字典互轉(zhuǎn)代碼實(shí)例詳解,需要的朋友可以參考下2020-02-02

