Django 實(shí)現(xiàn)圖片上傳和下載功能
原生上傳圖片方式
#新建工程 python manage.py startapp test30 #修改 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stu' ] #修改urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'student/',include('stu.urls')), ] #新增加 stu/urls.py #coding:utf-8 from django.conf.urls import url import views urlpatterns = [ url(r'^$',views.index_view) ] #編輯 stu/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render # Create your views here. #原生上傳文件方式 def index_view(request): if request.method == 'GET': return render(request,'index.html') elif request.method == 'POST': #獲取請(qǐng)求參數(shù) uname = request.POST.get('uname','') photo = request.FILES.get('photo','') print photo.name import os print os.getcwd() if not os.path.exists('media'): os.mkdir('media') #拼接路徑 with open(os.path.join(os.getcwd(),'media',photo.name),'wb') as fw: # photo.read() #一次性讀取文件到內(nèi)存 # fw.write(photo.read()) #分塊讀取,性能高 for ck in photo.chunks(): fw.write(ck) return HttpResponse('It is post request,上傳成功') else: return HttpResponse('It is not post and get request!') #新增加模板文件 templates/index.html <!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> <label for="ua">姓名: </label> <input type="text" name="uname" id="ua"/> </p> <p> <label for="ph">頭像: </label> <input type="file" name="photo" id="ph"/> </p> <p>      <input type="submit" value="注冊(cè)"/> </p> </form> </body> </html> #效果如下: 訪問(wèn): http://127.0.0.1:8000/student/
Django 圖片上傳方式
需求: 效果: 訪問(wèn) http://127.0.0.1:8000/student/ 通過(guò)注冊(cè)將姓名、頭像地址傳入數(shù)據(jù)庫(kù)中; 訪問(wèn) http://127.0.0.1:8000/student/showall 將數(shù)據(jù)庫(kù)信息通過(guò)表格形式展示 ###過(guò)程 #修改 settings.py ,templates 新增加 'django.template.context_processors.media' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media' ], }, }, ] 末尾增加: # global_settings #指定上傳文件存儲(chǔ)相對(duì)路徑(讀取文件) MEDIA_URL = '/media/' #指定上傳文件存儲(chǔ)絕對(duì)路徑(存儲(chǔ)文件) MEDIA_ROOT = os.path.join(BASE_DIR,'media') #創(chuàng)建數(shù)據(jù)庫(kù)模型 stu/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Student(models.Model): sno = models.AutoField(primary_key=True) sname = models.CharField(max_length=30) photo = models.ImageField(upload_to='imgs') def __unicode__(self): return u'Student:%s'%self.sname #生成數(shù)據(jù)庫(kù)遷移文件,查看數(shù)據(jù)庫(kù)表結(jié)構(gòu) python makemigrations stu python migrate #修改 urls.py 因?yàn)轱@示問(wèn)題,增加 DEBUG 內(nèi)容 from django.conf.urls import url, include from django.contrib import admin from test30.settings import DEBUG, MEDIA_ROOT urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'student/',include('stu.urls')), ] from django.views.static import serve if DEBUG: urlpatterns+=url(r'^media/(?P<path>.*)/$', serve, {"document_root": MEDIA_ROOT}), #修改 urls, stu/urls.py #coding:utf-8 from django.conf.urls import url import views urlpatterns = [ url(r'^$',views.index_view), url(r'^upload/$',views.upload_view), url(r'^showall/$',views.showall_view) ] # 修改 stu/views.py #django 上傳文件方式 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() print stus return render(request,'show.html',{'stus':stus}) # 修改 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/student/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} <p> <label for="ua">姓名: </label> <input type="text" name="uname" id="ua"/> </p> <p> <label for="ph">頭像: </label> <input type="file" name="photo" id="ph"/> </p> <p>      <input type="submit" value="注冊(cè)"/> </p> </form> </body> </html> # 增加模板文件 show.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table width="500px" border="1" cellspacing="0"> <tr> <th>編號(hào)</th> <th>姓名</th> <th>頭像</th> <th>操作</th> </tr> {% for stu in stus %} <tr> <td>{{ forloop.counter }}</td> <td>{{ stu.sname }}</td> <td><img style="width: 200px;" src="{{ MEDIA_URL }}{{ stu.photo }}"/></td> <td> 下載</td> </tr> {% endfor %} </table> </body> </html> 效果圖: http://127.0.0.1:8000/student/ 注冊(cè)實(shí)現(xiàn)數(shù)據(jù)庫(kù)錄入操作(點(diǎn)擊提交通過(guò)index.html 中action="/student/upload/" 將url 轉(zhuǎn)發(fā)至函數(shù)upload_view ,實(shí)現(xiàn)上傳功能) http://127.0.0.1:8000/student/showall/ 實(shí)現(xiàn)數(shù)據(jù)庫(kù)信息展示
圖片下載功能
### 需求 在顯示頁(yè)面點(diǎn)擊下載實(shí)現(xiàn)圖片的下載功能 過(guò)程: #修改 show.html ,加入 下載的超鏈接 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table width="500px" border="1" cellspacing="0"> <tr> <th>編號(hào)</th> <th>姓名</th> <th>頭像</th> <th>操作</th> </tr> {% for stu in stus %} <tr> <td>{{ forloop.counter }}</td> <td>{{ stu.sname }}</td> <td><img style="width: 200px;" src="{{ MEDIA_URL }}{{ stu.photo }}"/></td> <td><a href="/student/download/?photo={{ stu.photo }}" rel="external nofollow" >下載</a></td> </tr> {% endfor %} </table> </body> </html> #因?yàn)?show.html href="/student/download ,所以要修改urls #修改 stu/urls.py,新增加 url url(r'^download/$',views.download_view) #修改 stu/views.py def download_view(request): # 獲取請(qǐng)求參數(shù)(圖片存儲(chǔ)位置) imgs/5566.jpg photo = request.GET.get('photo','') print photo # 獲取圖片文件名5566.jpg ; rindex 為字符 '/' 在 photo 中最后出現(xiàn)的位置索引;例如 # txt = "imgs/5566.jpg" # x = txt.rindex("/") # print txt[x + 1:] 輸出結(jié)果為 5566.jpg filename = photo[photo.rindex('/')+1:] print filename #開啟一個(gè)流 import os path = os.path.join(os.getcwd(),'media',photo.replace('/','\\')) print path with open(path,'rb') as fr: response = HttpResponse(fr.read()) response['Content-Type']='image/png' response['Content-Disposition'] = 'attachment;filename=' + filename return response #訪問(wèn) http://127.0.0.1:8000/student/showall/ ,點(diǎn)擊下載
以上就是Django 實(shí)現(xiàn)圖片上傳和下載功能的詳細(xì)內(nèi)容,更多關(guān)于Django 圖片上傳和下載的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Django實(shí)現(xiàn)圖片上傳功能步驟解析
- 在django中圖片上傳的格式校驗(yàn)及大小方法
- django mysql數(shù)據(jù)庫(kù)及圖片上傳接口詳解
- Django 實(shí)現(xiàn)圖片上傳和顯示過(guò)程詳解
- Django框架文件上傳與自定義圖片上傳路徑、上傳文件名操作分析
- django將圖片上傳數(shù)據(jù)庫(kù)后在前端顯式的方法
- Django后臺(tái)獲取前端post上傳的文件方法
- 利用django如何解析用戶上傳的excel文件
- Python+django實(shí)現(xiàn)文件上傳
- django實(shí)現(xiàn)圖片上傳數(shù)據(jù)庫(kù)并顯示
相關(guān)文章
Python實(shí)現(xiàn)命令行通訊錄實(shí)例教程
這篇文章主要介紹怎樣編寫了一段命令行通訊錄的小程序。下面是編寫的思路以及代碼,歡迎感興趣的同學(xué)交流探討。2016-08-08python 回調(diào)函數(shù)和回調(diào)方法的實(shí)現(xiàn)分析
這篇文章主要介紹了python 回調(diào)函數(shù)和回調(diào)方法的實(shí)現(xiàn)分析,需要的朋友可以參考下2016-03-03使用python實(shí)現(xiàn)希爾、計(jì)數(shù)、基數(shù)基礎(chǔ)排序的代碼
希爾排序是一個(gè)叫希爾的數(shù)學(xué)家提出的一種優(yōu)化版本的插入排序。這篇文章主要介紹了使用python實(shí)現(xiàn)希爾、計(jì)數(shù)、基數(shù)基礎(chǔ)排序,需要的朋友可以參考下2019-12-12Python Pandas中根據(jù)列的值選取多行數(shù)據(jù)
這篇文章主要介紹了Python Pandas中根據(jù)列的值選取多行數(shù)據(jù)的實(shí)例代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì) ,需要的朋友可以參考下2019-07-07python實(shí)現(xiàn)單線程多任務(wù)非阻塞TCP服務(wù)端
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)單線程多任務(wù)非阻塞TCP服務(wù)端的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06關(guān)于jieba.cut與jieba.lcut的區(qū)別及說(shuō)明
這篇文章主要介紹了關(guān)于jieba.cut與jieba.lcut的區(qū)別及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05