django-admin.py startproject upload
进入upload项目目录,创建home应用
cd upload ./manage.py startapp home
在home应用目录下创建一个模板目录
mkdir home/templates
进行项目基本设置
vi upload/settings.py
INSTALLED_APPS = ( # ... 'home', )
import os #... TEMPLATE_DIRS = ( # ... os.path.join(os.path.realpath(os.path.dirname(__file__)), 'home/templates'), )
vi upload/urls.py
urlpatterns = patterns('', # ... url(r'^$', 'home.views.index', name='home'), url(r'^upload', 'home.views.upload'), )
编辑home应用的views.py文件
vi home/views.py
from django.views.decorators.csrf import csrf_protect from django.shortcuts import render_to_response, render @csrf_protect def index(request): """docstring for index""" return render(request, 'index.html', {'title': 'test page'}) def upload(request): if request.method == 'POST': f = handle_uploaded_file(request.FILES['pic']) return render_to_response('upload.html', {'file':f}) def handle_uploaded_file(f): with open(f.name, 'wb+') as info: for chunk in f.chunks(): info.write(chunk) return f
在home应用的templates中添加两个模板文件
index.html
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8" /> <title>{{ title }}</title> </head> <body> <h1>Upload File</h1> <form action="/upload" method="post" enctype="multipart/form-data" accept-charset="utf-8"> {% csrf_token %} <input type="file" name="pic" value="" /> <button>Submit</button> </form> </body> </html>
upload.html
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8" /> <title>Upload Successed</title> </head> <body> <h1>Upload file successed.</h1> <pre> filename: {{ file.name }} filesize: {{ file.size }} bytes </pre> <a href="/">back</a> </body> </html>
开始测试
./manage.py runserver