這篇文章主要為大家展示了“Django如何實(shí)現(xiàn)文件上傳與下載功能”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Django如何實(shí)現(xiàn)文件上傳與下載功能”這篇文章吧。

具體內(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ù)中并查詢所有信息
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)建模板 顯示查詢到所有的信息
<!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 response2.修改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é)生照片下載到本地
以上是“Django如何實(shí)現(xiàn)文件上傳與下載功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
當(dāng)前標(biāo)題:Django如何實(shí)現(xiàn)文件上傳與下載功能-創(chuàng)新互聯(lián)
文章源于:http://chinadenli.net/article32/eghpc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、動(dòng)態(tài)網(wǎng)站、靜態(tài)網(wǎng)站、網(wǎng)站建設(shè)、面包屑導(dǎo)航、響應(yīng)式網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容