title: 500: Internal Server Error. Tornado Upload App
body: <p>I was in the need of letting users upload pictures from a PhoneGap application using Tornado on my server, so I used a piece of code found on another question:
  <a href="https://stackoverflow.com/questions/11909397/how-to-upload-an-image-with-python-tornado-from-an-html-form">How to upload an image with python-tornado from an HTML form?</a></p>
  
  <p>The code as seen there works perfectly fine. But sadly what I'm sending to the server isn't exactly a file, but a base64 encoded string. So I up a "test lab" on UNIX machine did some modifications on the code, so I would receive the string and another agrgument I needed to use to name the file after decoding the string. When I launch the service it starts normally, but when I try to access it from the browser, it instantly show 500: Internal Server Error. The only part of the code I modified was the UploadHandler, everything else is exactly the same. I'm pretty new to python so I know probably I did something wrong. Any help would be appreciated.</p>
  
  <pre><code>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()
  </code></pre>