如何从 HTML 表单上传带有 python-tornado 的图像? [英] How to upload an image with python-tornado from an HTML form?

查看:30
本文介绍了如何从 HTML 表单上传带有 python-tornado 的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I saw examples that used pycurl, but could not be sure if this is the way to go with? Some examples will help. Thanks.

推荐答案

这里是 演示应用程序实现龙卷风上传.

Here is demo application that implements tornado upload.

这是服务器代码:

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[][0] 中的文件内容.

The only thing, you have to understand from this code, that file content located in 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".

When working with files - be sure, that form has enctype="multipart/form-data".

这篇关于如何从 HTML 表单上传带有 python-tornado 的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆