17

我看到了使用 pycurl 的示例,但不确定这是否是可行的方法?一些例子会有所帮助。谢谢。

4

5 回答 5

23

这是实现龙卷风上传的演示应用程序。

这是服务器代码:

import tornado.httpserver, tornado.ioloop, tornado.options, tornado.web, os.path, random, string
from tornado.options import define, options

define("port", default=8888, help="run on the given port", type=int)

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", IndexHandler),
            (r"/upload", UploadHandler)
        ]
        tornado.web.Application.__init__(self, handlers)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("upload_form.html")

class UploadHandler(tornado.web.RequestHandler):
    def post(self):
        file1 = self.request.files['file1'][0]
        original_fname = file1['filename']
        extension = os.path.splitext(original_fname)[1]
        fname = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6))
        final_filename= fname+extension
        output_file = open("uploads/" + final_filename, 'w')
        output_file.write(file1['body'])
        self.finish("file" + final_filename + " is uploaded")

def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

唯一的事情,你必须从这段代码中理解,文件内容位于self.request.files[<file_input_name>][0].

这是html代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
<title>Tornado Upload Application</title>
</head>
<body>
<p><h1>Tornado Upload App</h1></p>
<form enctype="multipart/form-data" action="/upload" method="post">
File: <input type="file" name="file1" />
<br />
<br />
<input type="submit" value="upload" />
</form>

处理文件时 - 请确保该表单具有enctype="multipart/form-data".

于 2012-08-11T10:15:43.567 回答
17

这很简单:

<form action="/file" methods="POST"><!--your code--></form>

在 Python 中:

class FileHandler(tornado.web.RequestHandler):
    # get post data
    file_body = self.request.files['filefieldname'][0]['body']
    img = Image.open(io.StringIO(file_body))
    img.save("../img/", img.format)

但不推荐,因为所有上传的数据都加载在 RAM 中;最好的方法是使用 nginx 加载模块,但这很复杂。

于 2012-08-11T04:44:51.743 回答
6

以前的代码返回错误的文件名和错误的编码。以下代码有效:

import tornado.httpserver, tornado.ioloop, tornado.options, tornado.web, os.path, random, string




class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", IndexHandler),
            (r"/upload", UploadHandler)
        ]
        tornado.web.Application.__init__(self, handlers)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("tornadoUpload.html")

class UploadHandler(tornado.web.RequestHandler):
    def post(self):
        file1 = self.request.files['file1'][0]
        original_fname = file1['filename']

        output_file = open("uploads/" + original_fname, 'wb')
        output_file.write(file1['body'])

        self.finish("file " + original_fname + " is uploaded")

settings = {
'template_path': 'templates',
'static_path': 'static',
"xsrf_cookies": False

}
application = tornado.web.Application([
   (r"/", IndexHandler),
            (r"/upload", UploadHandler)


], debug=True,**settings)



print "Server started."
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
于 2013-05-12T21:58:25.770 回答
4

使用 [''] 语法访问文件属性时遇到了麻烦,不知道为什么,但我切换到点语法并能够读取数据。我在 Windows 机器上,所以我还必须将 'open("static/public/" + file_name, 'w')' 更改为 'open("static/public/" + file_name, 'wb')'。如果没有“wb”,文件就会损坏。

def uploadFile(self,input_name,file_type):
            a_file = self.request.files[input_name][0]
            extension = os.path.splitext(a_file.filename)[1]

            if file_type is 'photo':
                type_list = ['.png','.jpg','.jpeg','.gif']
            elif file_type is 'attachment':
                type_list = ['.pdf','.doc','.docx','.xls']

            if extension in type_list:
                file_name = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(16))
                output_file = open("static/public/" + file_name + extension, 'wb')
                output_file.write(a_file.body)
                return (a_file.filename + " has been uploaded.")
于 2014-01-17T14:28:49.737 回答
0

tornado.web.RequestHandlerself.request.files方法。结果就像

{u'file': [{'body':FILEBODY, 'content_type':CONTENT_TYPE, 'filename': FILENAME}],...}
于 2017-03-03T08:18:12.607 回答