Django 는 이미지 업로드 와 다운로드 기능 을 실현 합 니 다.
#
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':
#
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() #
# 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=" "/>
</p>
</form>
</body>
</html>
# :
: http://127.0.0.1:8000/student/
Django 이미지 업로드 방식
:
: http://127.0.0.1:8000/student/ 、 ;
http://127.0.0.1:8000/student/showall
###
# 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
# ( )
MEDIA_URL = '/media/'
# ( )
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
# 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
# ,
python makemigrations stu
python migrate
# urls.py , DEBUG
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','')
#
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=" "/>
</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> </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/ ( index.html action="/student/upload/" url upload_view , )
http://127.0.0.1:8000/student/showall/
사진 다운로드 기능
###
:
# 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> </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>
# show.html href="/student/download , urls
# stu/urls.py, url
url(r'^download/$',views.download_view)
# stu/views.py
def download_view(request):
# ( ) imgs/5566.jpg
photo = request.GET.get('photo','')
print photo
# 5566.jpg ; rindex '/' photo ;
# txt = "imgs/5566.jpg"
# x = txt.rindex("/")
# print txt[x + 1:] 5566.jpg
filename = photo[photo.rindex('/')+1:]
print filename
#
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
# http://127.0.0.1:8000/student/showall/ ,
이상 은 Django 가 이미지 업로드 와 다운로드 기능 을 실현 하 는 상세 한 내용 입 니 다.Django 이미지 업로드 와 다운로드 에 관 한 자 료 는 다른 관련 글 을 주목 하 세 요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Django 라우팅 계층 URLconf 작용 및 원리 해석URL 구성(URLconf)은 Django가 지원하는 웹 사이트의 디렉토리와 같습니다.그것의 본질은 URL과 이 URL을 호출할 보기 함수 사이의 맵표입니다. 위의 예제에서는 URL의 값을 캡처하고 위치 매개 변수로...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.