django python 文件上传【P
1、URL
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
url(r'^upload/$', views.upload_file, name='upload'),
)
2、FORM类
vi forms.py
from Django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length = 50)
file = forms.FileField()
3、视图:
--上传处理
def handle_uploaded_file(f,title):
filename = "name.txt"
if title != "":
filename = title
print "upload file's name is " + f.name
with open('/tmp/'+filename,'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
print "upload......"
if form.is_valid():
print "is valid........"
handle_uploaded_file(request.FILES['file'],request.POST['title'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render(request, 'polls/upload.html', {'form': form})
4、模板 upload.html
<html>
<head>
<title>file upload</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="{% url 'polls:upload' %}">{% csrf_token %}
File Name:<input type="text" name="title" /><br />
<input type="file" name="file"/><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
相关文章