Reputation: 306
I'm trying to write a very simple python script based on tornado web server to upload a file. But I'm getting 'KeyError' though the key is in the html form is OK.
Here is the python code just to see the uploaded file name.
import tornado.ioloop
import tornado.web
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write("Bismillahir Rahmanir Raheem")
self.render('form.html')
class UploadHandler(tornado.web.RequestHandler):
def post(self):
self.write("Alhamdulillah, here")
if self.request.files is not None:
self.write("Inside the if")
uploadFile = self.request.files['my_file'][0]
self.write(uploadFile['filename'])
def make_app():
return tornado.web.Application([
(r"/", IndexHandler),
(r"/upload", UploadHandler)
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
And the html form is as below:
<html>
<head>
<title>Testing file upload</title>
</head>
<body>
<h1>Testing file upload</h1>
<form enctype="multipart/formdata" method="post" action="/upload">
<input type="file" name="my_file"/>
<input type="Submit" name="upload" value="Upload"/>
</form>
</body>
</html>
But each time I select a file and press Upload button I get the
500: Internal Server Error
And at the PyCharm editor I get the following error: File "C:/Users/Mushfique/Desktop/file-upload/upload.py", line 14, in post uploadFile = self.request.files['my_file'][0]
KeyError: 'my_file' ERROR:tornado.access:500 POST /upload (::1) 1.00ms
Though in the html form I've used 'my_file' as the file input field name.
Upvotes: 0
Views: 776
Reputation: 21779
You've a typo there:
<form enctype="multipart/formdata" ...>
^^^^ this is a typo
It should be multipart/form-data
(note the hyphen).
Upvotes: 1