溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django如何實(shí)現(xiàn)文件上傳與下載功能

發(fā)布時間:2021-07-24 11:57:58 來源:億速云 閱讀:182 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“Django如何實(shí)現(xiàn)文件上傳與下載功能”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(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)建一個
  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('注冊成功')
 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="注冊"></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>編號</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 讀取后臺上傳的文件

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é)生照片下載到本地

以上是“Django如何實(shí)現(xiàn)文件上傳與下載功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI