Django學(xué)習(xí)之文件上傳與下載
本文實(shí)例為大家分享了Django文件上傳與下載的具體代碼,供大家參考,具體內(nèi)容如下
文件上傳
1.新建django項(xiàng)目,創(chuàng)建應(yīng)用stu: python manage.py startapp stu
2.在配置文件setting.py INSTALLED_APP 中添加新創(chuàng)建的應(yīng)用stu
3.配置urls,分別在test\urls 和子路由stu\urls 中
#test\urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^student/',include('stu.urls')) ] #stu\urls from django.conf.urls import url import views urlpatterns=[ url(r'^$',views.index_view) ]
4.創(chuàng)建視圖文件index_view.py
def index_view(request): if request.method=='GET': return render(request,'index.html') elif request.method=='POST': uname = request.POST.get('uname','') photo = request.FILES.get('photo','') import os if not os.path.exists('media'): #判斷是否存在文件media,不存在則創(chuàng)建一個(gè) os.makedirs('media') with open(os.path.join(os.getcwd(),'media',photo.name),'wb') as fw: #以讀的方式打開目錄為/media/photo.name 的文件 別名為fw fw.write(photo.read()) #讀取photo文件并將其寫入(一次性讀取完) for chunk in fw.chunks: fw.write(chunk) return HttpResponse('注冊(cè)成功') else: return HttpResponse('頁面跑丟了,稍后再試!')
5.創(chuàng)建模板文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/student/" method="post" enctype="multipart/form-data"> {% csrf_token %} <p> <lable>姓名:<input type="text" name ='uname'></lable> </p> <p> <lable>頭像:<input type="file" name ='photo'></lable> </p> <p> <lable><input type="submit" value="注冊(cè)"></lable> </p> </form> </body> </html>
文件存在數(shù)據(jù)庫中并查詢所有信息
1.創(chuàng)建模型類
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. from django.db import models class Student(models.Model): sid = models.AutoField(primary_key=True) sname = models.CharField(max_length=30) photo = models.ImageField(upload_to='img') class Meta: db_table='t_stu' def __unicode__(self): return u'Student:%s' %self.sname
2.修改配置文件setting.py 添加新內(nèi)容
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media')
3.通過創(chuàng)建的模型類 來映射數(shù)據(jù)庫表
python mange.py makemigrations stu
python mange.py migrate
4.添加新的子路由地址
urlpatterns=[ url(r'^$',views.index_view), url(r'^upload/$',views.upload_view), url(r'^show/$',views.showall_view) ]
5.在views文件中添加新的函數(shù) showall_view()
def upload_view(request): uname = request.POST.get('uname','') photo = request.FILES.get('photo','') #入庫操作 Student.objects.create(sname = uname,photo=photo) return HttpResponse('上傳成功') def showall_view(request): stus = Student.objects.all() return render(request,'show.html',{'stus':stus})
6.創(chuàng)建模板 顯示查詢到所有的信息
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1" width="500px" cellspacing="0"> <tr> <th>編號(hào)</th> <th>姓名</th> <th>圖片</th> <th>操作</th> </tr> <tr> {% for stu in stus %} <td>{{ forloop.counter }}</td> <td>{{ stu.sname }}</td> <td><img src="{{ MEDIA_URL}}{{ stu.photo }}"/> </td> <td><a href="#" rel="external nofollow" >操作</a></td> {% endfor %} </tr> </table> </body> </html>
7.配置根路由 test\urls.py 讀取后臺(tái)上傳的文件
from django.views.static import serve if DEBUG: urlpatterns+=url(r'^media/(?P<path>.*)/$', serve, {"document_root": MEDIA_ROOT}),
8.再次修改配置文件setting.py 在TEMPLATE中添加新的內(nèi)容 可以獲取到media中的內(nèi)容
'django.template.context_processors.media'
9.訪問127.0.0.1:8000/student/ 上傳學(xué)生信息
訪問127.0.0.1:8000/student/show/ 查看所有學(xué)生的信息
文件的下載
1.配置子路由 訪問views.py 下的download_view()函數(shù)
urlpatterns=[ url(r'^$',views.index_view), url(r'^upload/$',views.upload_view), url(r'^show/$',views.showall_view), url(r'^download/$',views.download_view) ]
import os def download_view(request): #獲取文件存放的位置 filepath = request.GET.get('photo','') print filepath #獲取文件的名字 filename = filepath[filepath.rindex('/')+1:] print filename path = os.path.join(os.getcwd(),'media',filepath.replace('/','\\')) with open(path,'rb') as fr: response = HttpResponse(fr.read()) response['Content-Type'] = 'image/png' # 預(yù)覽模式 response['Content-Disposition'] = 'inline;filename=' + filename # 附件模式 response['Content-Disposition']='attachment;filename='+filename return response
2.修改show.html 文件中下載欄的超鏈接地址
<tr> {% for stu in stus %} <td>{{ forloop.counter }}</td> <td>{{ stu.sname }}</td> <td><img src="{{ MEDIA_URL}}{{ stu.photo }}"/> </td> <td><a href="/student/download/?photo={{ stu.photo }}" rel="external nofollow" >下載</a></td> {% endfor %} </tr>
3.訪問127.0.0.1:8000/studnet/show/ 查看學(xué)生信息
點(diǎn)擊操作欄中的下載 即可將學(xué)生照片下載到本地
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python 同時(shí)運(yùn)行多個(gè)程序的實(shí)例
今天小編就為大家分享一篇python 同時(shí)運(yùn)行多個(gè)程序的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01Python的Pillow庫進(jìn)行圖像文件處理(圖文詳解)
本文詳解的講解了使用Pillow庫進(jìn)行圖片的簡單處理,使用PyCharm開發(fā)Python的詳細(xì)過程和各種第三方庫的安裝與使用。感興趣的可以了解一下2021-11-11python實(shí)現(xiàn)帶驗(yàn)證碼網(wǎng)站的自動(dòng)登陸實(shí)現(xiàn)代碼
本例所登錄的某網(wǎng)站需要提供用戶名,密碼和驗(yàn)證碼,在此使用了python的urllib2直接登錄網(wǎng)站并處理網(wǎng)站的Cookie2015-01-01Python 工具類實(shí)現(xiàn)大文件斷點(diǎn)續(xù)傳功能詳解
用python進(jìn)行大文件下載的時(shí)候,一旦出現(xiàn)網(wǎng)絡(luò)波動(dòng)問題,導(dǎo)致文件下載到一半。如果將下載不完全的文件刪掉,那么又需要從頭開始,如果連續(xù)網(wǎng)絡(luò)波動(dòng),是不是要頭禿了。本文提供斷點(diǎn)續(xù)傳下載工具方法,希望可以幫助到你2021-10-10Python使用Supervisor來管理進(jìn)程的方法
這篇文章主要介紹了Python使用Supervisor來管理進(jìn)程的方法,涉及Supervisor的相關(guān)使用技巧,需要的朋友可以參考下2015-05-05Python簡單過濾字母和數(shù)字的方法小結(jié)
這篇文章主要介紹了Python簡單過濾字母和數(shù)字的方法,涉及Python基于內(nèi)置函數(shù)與正則表達(dá)式進(jìn)行字母和數(shù)字過濾的相關(guān)操作技巧,需要的朋友可以參考下2019-01-01Python實(shí)現(xiàn)檢測(cè)照片中的人臉數(shù)
這篇文章主要為大家詳細(xì)介紹了如何利用Python語言實(shí)現(xiàn)檢測(cè)照片中共有多少張人臉,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-08-08python機(jī)器學(xué)習(xí)庫xgboost的使用
這篇文章主要介紹了python機(jī)器學(xué)習(xí)庫xgboost的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01