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>
    &emsp;&emsp;&emsp;&emsp;&emsp;<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>
    &emsp;&emsp;&emsp;&emsp;&emsp;<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 이미지 업로드 와 다운로드 에 관 한 자 료 는 다른 관련 글 을 주목 하 세 요!

좋은 웹페이지 즐겨찾기