在django里面上传文件
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
# Create your views here. # coding=utf- 8
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.csrf import csrf_protect
#上传文件 @csrf_exempt @csrf_protect def upload_tomcat_config_file(request): from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length= 1000000 )
file = forms.FileField()
if request.method == "GET" :
data= 'get'
if request.method == "POST" :
f = handle_uploaded_file(request.FILES[ 't_file' ])
return render_to_response( 'upload_config_file.html' ,context_instance=RequestContext(request))
# return HttpResponse(data)
def handle_uploaded_file(f): f_path= '/srv/salt/config/' +f.name
with open(f_path, 'wb+' ) as info:
print f.name
for chunk in f.chunks():
info.write(chunk)
return f
#上传文件结束 |
upload_config_file.html内容如下
1
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!DOCTYPE HTML> < html lang = "en" >
< head >
< meta charset = "utf-8" />
< title >` title `</ title >
</ head >
< body >
< a >配置文件上传</ a >
< form action = "/opsapi/command/up_file" method = "post" enctype = "multipart/form-data" accept-charset = "utf-8" >
{% csrf_token %}
< input type = "file" name = "t_file" value = "" />
< button >Submit</ button >
</ form >
</ body >
</ html >
|
url的配置就不写了,效果如下
1
|
|
上传到服务器上面
我这里是用时间来保存的,代码和上面稍有不同
本文转自it你好 51CTO博客,原文链接:http://blog.51cto.com/itnihao/1337762,如需转载请自行联系原作者