手机版
你好,游客 登录 注册
背景:
阅读新闻

Django上传文件代码

[日期:2013-12-24] 来源:Linux社区  作者:itnihao [字体:大 中 小]

在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
#上传文件结束

upload_config_file.html内容如下

<!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的配置就不写了,效果如下


上传到服务器上面

我这里是用时间来保存的,代码和上面稍有不同

Django 的详细介绍:请点这里
Django 的下载地址:请点这里

推荐阅读:

Ubuntu Server 12.04 安装Nginx+uWSGI+Django环境 http://www.linuxidc.com/Linux/2012-05/60639.htm

Django实战教程 http://www.linuxidc.com/Linux/2013-09/90277.htm

Django Python MySQL Linux 开发环境搭建 http://www.linuxidc.com/Linux/2013-09/90638.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款