我需要让用户在我的服务器上使用Tornado从PhoneGap应用程序上传图片,所以我在另一个问题上使用了一段代码: How to upload an image with python-tornado from an HTML form?
在那里看到的代码完美无缺。但遗憾的是,我发送到服务器的并不是一个文件,而是一个base64编码的字符串。所以我在UNIX机器上的“测试实验室”对代码做了一些修改,所以我会收到字符串和我需要用来在解码字符串后命名文件的另一个agrgument。当我启动服务时它正常启动,但是当我尝试从浏览器访问它时,它会立即显示500:内部服务器错误。我修改的代码中唯一的部分是UploadHandler,其他一切都完全相同。我对python很新,所以我知道我做错了。任何帮助将不胜感激。
import tornado.httpserver, tornado.ioloop, tornado.web, os.path, random, string
from tornado.options import (define, options)
define("port", default=8884, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", IndexHandler),
(r"/upload", UploadHandler)
]
settings = {
'template_path': 'templates',
'static_path': 'static',
'xsrf_cookies': False
}
tornado.web.Application.__init__(self, handlers, **settings)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("subir-string.html")
class UploadHandler(tornado.web.RequestHandler):
def post(self):
b64string = self.get_argument("imageData","")
v_id = self.get_argument("id","")
if b64string:
try:
new_name = "uploads/%s.jpg" % v_id
c = 0
while os.path.isfile(new_name):
base, ext = os.path.splitext(new_name)
new_name = "uploads/%s-%s%s" % (base, c, ext)
c= c + 1
output_file = open(new_name, 'w')
output_file.write(base64.decodestring(b64string))
except Exception as e:
print "Error: %s"%(e)
self.finish(" Can't process request")
else:
self.finish(" File Uploaded " + new_name)
def main():
tornado.options.parse_command_line()
app = Application()
app.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()