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: #以讀的方式打開(kāi)目錄為/media/photo.name 的文件 別名為fw
fw.write(photo.read()) #讀取photo文件并將其寫(xiě)入(一次性讀取完)
for chunk in fw.chunks:
fw.write(chunk)
return HttpResponse('注冊(cè)成功')
else:
return HttpResponse('頁(yè)面跑丟了,稍后再試!')
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ù)庫(kù)中并查詢(xún)所有信息
1.創(chuàng)建模型類(lèi)
# -*- 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.通過(guò)創(chuàng)建的模型類(lèi) 來(lái)映射數(shù)據(jù)庫(kù)表
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','')
#入庫(kù)操作
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)建模板 顯示查詢(xún)到所有的信息
<!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.訪問(wèn)127.0.0.1:8000/student/ 上傳學(xué)生信息
訪問(wèn)127.0.0.1:8000/student/show/ 查看所有學(xué)生的信息
文件的下載
1.配置子路由 訪問(wèn)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.訪問(wèn)127.0.0.1:8000/studnet/show/ 查看學(xué)生信息
點(diǎn)擊操作欄中的下載 即可將學(xué)生照片下載到本地
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在Python中使用SimpleParse模塊進(jìn)行解析的教程
這篇文章主要介紹了在Python中使用SimpleParse模塊進(jìn)行解析的教程,文章來(lái)自于IBM官方的開(kāi)發(fā)者技術(shù)文檔,需要的朋友可以參考下2015-04-04
Python實(shí)現(xiàn)批量修改Word文檔中圖片大小并居中對(duì)齊
這篇文章主要介紹了如何利用Python實(shí)現(xiàn)批量修改Word文檔中圖片大小并居中對(duì)齊,文中通過(guò)代碼示例給大家講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-08-08
Python中構(gòu)建終端應(yīng)用界面利器Blessed模塊的使用
Blessed?庫(kù)作為一個(gè)輕量級(jí)且功能強(qiáng)大的解決方案,開(kāi)始在開(kāi)發(fā)者中贏得口碑,今天,我們就一起來(lái)探索一下它是如何讓終端UI開(kāi)發(fā)變得輕松而高效的吧2025-01-01
python調(diào)用MySql保姆級(jí)圖文教程(包會(huì)的)
MySQL是當(dāng)今市場(chǎng)上最受歡迎的數(shù)據(jù)庫(kù)系統(tǒng)之一,由于大多數(shù)應(yīng)用程序需要以某種形式與數(shù)據(jù)交互,因此像Python這樣的編程語(yǔ)言提供了用于存儲(chǔ)和訪問(wèn)這些數(shù)據(jù)的工具,這篇文章主要給大家介紹了關(guān)于python調(diào)用MySql的相關(guān)資料,需要的朋友可以參考下2024-12-12
Python Pandas模塊實(shí)現(xiàn)數(shù)據(jù)的統(tǒng)計(jì)分析的方法
在上一篇講了幾個(gè)常用的“Pandas”函數(shù)之后,今天小編就為大家介紹一下在數(shù)據(jù)統(tǒng)計(jì)分析當(dāng)中經(jīng)常用到的“Pandas”函數(shù)方法,希望能對(duì)大家有所收獲,需要的朋友可以參考下2021-06-06
使用Python防止SQL注入攻擊的實(shí)現(xiàn)示例
這篇文章主要介紹了使用Python防止SQL注入攻擊的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
PyTorch?Distributed?Data?Parallel使用詳解
這篇文章主要為大家介紹了PyTorch?Distributed?Data?Parallel使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
python?tkinter實(shí)現(xiàn)彈窗的輸入輸出
這篇文章主要為大家詳細(xì)介紹了python?tkinter實(shí)現(xiàn)彈窗的輸入輸出,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02

