`
shaojiashuai123456
  • 浏览: 265923 次
  • 性别: Icon_minigender_1
  • 来自: 吉林
社区版块
存档分类
最新评论

python tornado 框架使用 (6)

阅读更多

                       tornaodo 实现文件上传

 

页面主要代码

<!DOCTYPE HTML>
<html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=gbk" />
       <link type="text/css" rel="stylesheet" href="/static/main.css" />
       <title></title>
    </head>
<body>
<script language="javascript" src="/static/js/jquery-3.3.1.min.js"></script>
<script language="javascript" src="/static/js/"></script>
<script language="javascript">
    function eventHandler(e, myargs) 
    {
        var _event = e[0] || window.event;
        myargs = myargs || {};

        switch(_event.target.id) 
        {
            case 'eva_old':
                alert("pre");
                break;
            case 'upload':
                alert("upload");
                formData = new FormData();
                formData.append("file", $("#file")[0].files[0]);
                $.ajax({
                      url:"upload",
                      type:"post",
                      data:formData,
                      contentType:false,
                      processData: false,
                      success:function(res)
                      {
                        var jsonRes = $.parseJSON(res);                        
                        var res = jsonRes["res"];
                        var content = "";
                        $.each(jsonRes.excle, function(i, item) 
                        {
                            content += "<tr>";
                            content += "<td width='100px'>";
                            content += item["city_name"];                     
                            content == "</td>";
                            content += "<td width='100px'>";
                            content += item["city_status"];                     
                            content += "</td>";
                            content += "</tr>";
                        });

                        $("#excle").html(content);
                        $("#fileres").html(res);
                        $("#num").html(jsonRes["num"]);
                      },
                      error:function(err){
                        alert("网络连接失败,稍后重试",err);
                      }
                });
                break;
        }
    }

</script>
    <div class="head">
    </div>
    <div class="list"> 
        <div id="div_user">
           <form enctype="multipart/form-data" method='post'>
              <input type='file' name='file' id="file"/><br/>
              <input type='button' value='上传' id="upload" onclick="eventHandler(arguments);"/>
           </form>  
        </div>
        <div>
           <p>num:<span id="num"></span></p>
        </div>
        <div id="fileres">
        </div>
        <div id="excle">
            <table id="excleTable">
            <table>
        </div>
    </div>
</body>
</html>

 

 

 

 

 

文件上传处理文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import json
import time
import logging
from unipath import Path
import traceback
import tornado.httpserver   
import tornado.ioloop   
import tornado.options   
import tornado.web   
import tornado.gen   
from tornado.options import define, options   
from tornado.httpclient import AsyncHTTPClient
from tornado.web import HTTPError
from tornado.iostream import StreamClosedError
import BusBannedCity

import common_logging
import common_urllib

logger = logging.getLogger(__name__)


class UploadHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def post(self):
        try:
            #获取当前时间
            time_now = int(time.time())
            #转换成localtime
            time_local = time.localtime(time_now)
            #转换成新的时间格式(2016-05-09 18:59:20)
            dt = time.strftime("%Y-%m-%d-%H:%M:%S",time_local)
            upload_path=os.path.join(os.path.dirname(__file__),'files')  #文件的暂存路径
            file_metas=self.request.files['file']    #提取表单中‘name’为‘file’的文件元数据
            #获取第一个文件
            meta = file_metas[0]
            filename=meta['filename']
            filename = dt + filename
            filepath=os.path.join(upload_path,filename)
            with open(filepath,'wb') as up:      #有些文件需要已二进制的形式存储,实际中可以更改
                up.write(meta['body'])

            res = BusBannedCity.parse_excel(filepath)   #文件解析函数
            self.write(json.dumps(res))                 #输出返回结果
        
        except:
            logger.error("%s" % traceback.format_exc());
        finally:
            logger.error("request[%s] time[%s]" % ( \
                    self.request.uri, \
                    self.request.request_time()
                ))
            self.finish()

 

   tornado 启动文件

   

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import json
import time
import logging
import common_logging
import common_urllib
from unipath import Path
import traceback

import tornado.httpserver   
import tornado.ioloop   
import tornado.options   
import tornado.web   
from tornado.options import define, options   
import file_eva_handler


logger = logging.getLogger(__name__)


class DefaultHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.render("index.html")


application = tornado.web.Application(handlers=[
    (r"/upload", file_eva_handler.UploadHandler),
    (r"/", DefaultHandler),
], template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"))


if __name__ == '__main__':
    pid = os.fork()
    if  pid < 0:
        sys.exit(1)
    elif pid > 0:
        sys.exit(0)
    else:
        logger.error("sys start...")

    server = tornado.httpserver.HTTPServer(application)
    server.bind(9999)
    server.start(4)
    tornado.ioloop.IOLoop.instance().start()

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics