亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Django學習之文件上傳與下載

 更新時間:2019年10月06日 11:26:00   作者:卍卐  
這篇文章主要為大家詳細介紹了Django學習之文件上傳與下載,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了Django文件上傳與下載的具體代碼,供大家參考,具體內(nèi)容如下

文件上傳

1.新建django項目,創(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/ 上傳學生信息

訪問127.0.0.1:8000/student/show/ 查看所有學生的信息

文件的下載

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/ 查看學生信息

點擊操作欄中的下載 即可將學生照片下載到本地

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python 同時運行多個程序的實例

    python 同時運行多個程序的實例

    今天小編就為大家分享一篇python 同時運行多個程序的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • Python的Pillow庫進行圖像文件處理(圖文詳解)

    Python的Pillow庫進行圖像文件處理(圖文詳解)

    本文詳解的講解了使用Pillow庫進行圖片的簡單處理,使用PyCharm開發(fā)Python的詳細過程和各種第三方庫的安裝與使用。感興趣的可以了解一下
    2021-11-11
  • python實現(xiàn)帶驗證碼網(wǎng)站的自動登陸實現(xiàn)代碼

    python實現(xiàn)帶驗證碼網(wǎng)站的自動登陸實現(xiàn)代碼

    本例所登錄的某網(wǎng)站需要提供用戶名,密碼和驗證碼,在此使用了python的urllib2直接登錄網(wǎng)站并處理網(wǎng)站的Cookie
    2015-01-01
  • Python 工具類實現(xiàn)大文件斷點續(xù)傳功能詳解

    Python 工具類實現(xiàn)大文件斷點續(xù)傳功能詳解

    用python進行大文件下載的時候,一旦出現(xiàn)網(wǎng)絡(luò)波動問題,導致文件下載到一半。如果將下載不完全的文件刪掉,那么又需要從頭開始,如果連續(xù)網(wǎng)絡(luò)波動,是不是要頭禿了。本文提供斷點續(xù)傳下載工具方法,希望可以幫助到你
    2021-10-10
  • Python使用Supervisor來管理進程的方法

    Python使用Supervisor來管理進程的方法

    這篇文章主要介紹了Python使用Supervisor來管理進程的方法,涉及Supervisor的相關(guān)使用技巧,需要的朋友可以參考下
    2015-05-05
  • 關(guān)于python常見異常以及處理方法

    關(guān)于python常見異常以及處理方法

    這篇文章主要介紹了關(guān)于python常見異常以及處理方法,python用異常對象(exception object)來表示異常情況。遇到錯誤后,會引發(fā)異常,需要的朋友可以參考下
    2023-04-04
  • Python簡單過濾字母和數(shù)字的方法小結(jié)

    Python簡單過濾字母和數(shù)字的方法小結(jié)

    這篇文章主要介紹了Python簡單過濾字母和數(shù)字的方法,涉及Python基于內(nèi)置函數(shù)與正則表達式進行字母和數(shù)字過濾的相關(guān)操作技巧,需要的朋友可以參考下
    2019-01-01
  • python編程項目中線上問題排查與解決

    python編程項目中線上問題排查與解決

    因為業(yè)務(wù)上的設(shè)計存在問題,導致數(shù)據(jù)庫表總是被鎖,而且是不定期的鎖定,導致服務(wù)器運行異常,今天就來跟大家說說該如何避免這種問題
    2021-11-11
  • Python實現(xiàn)檢測照片中的人臉數(shù)

    Python實現(xiàn)檢測照片中的人臉數(shù)

    這篇文章主要為大家詳細介紹了如何利用Python語言實現(xiàn)檢測照片中共有多少張人臉,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下
    2022-08-08
  • python機器學習庫xgboost的使用

    python機器學習庫xgboost的使用

    這篇文章主要介紹了python機器學習庫xgboost的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-01-01

最新評論