前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >django python 文件上传

django python 文件上传

作者头像
py3study
发布2020-01-14 19:53:33
7990
发布2020-01-14 19:53:33
举报
文章被收录于专栏:python3

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>

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/06/30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档