使用一个模型来处理上传文件
node2:/django/mysite/news/templates#cat upload.html
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form class="form-inline" role="form" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<div class="form-group">
<input type="file" name="file">
</div>
<div class="form-group">
<input type="submit" value="上传文件">
</div>
</form>
</div>
</div>
node2:/django/mysite/mysite#cat urls.py |grep upload
url(r'^upload/$',newview.upload,name='upload'),
def upload(request):
if request.method=="POST":
print '1111111---------------------'
print request.FILES['file']
print '1111111---------------------'
print '2222222---------------------'
print str(request.FILES['file'])
print '2222222---------------------'
handle_upload_file(request.FILES['file'],str(request.FILES['file']))
return HttpResponse('Successful') #此处简单返回一个成功的消息,在实际应用中可以返回到指定的页面中
else:
return render_to_response('upload.html')
def handle_upload_file(file,filename):
path='/tmp/' #上传文件的保存路径,可以自己指定任意的路径
if not os.path.exists(path):
os.makedirs(path)
with open(path+filename,'wb+')as destination:
for chunk in file.chunks():
print '-----------'
print chunk
print '-----------'
destination.write(chunk)