Django上傳文件代碼

在django裏面上傳文件
views.py
# 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 
#上傳文件結束html

upload_config_file.html內容以下django

<!DOCTYPE HTML> 
<html> 
<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>api

url的配置就不寫了,效果以下tomcat


上傳到服務器上面服務器

相關文章
相關標籤/搜索