Reputation: 18754
I am using the code below to upload zip files to a server. Everything works fine but the incoming zip files are corrupt for some reason. I know that the zip files are created correctly so they are not corrupt at the time of creation. Thus, there is something wrong with the server code.
In short, regular files like .txt
are uploaded just fine but the incoming zip files are corrupt. Anyone has an idea about why this may be happening ?
import tornado
import tornado.ioloop
import tornado.web
import os, uuid
__UPLOADS__ = "uploads/"
class Userform(tornado.web.RequestHandler):
def get(self):
self.render("form.html")
class Upload(tornado.web.RequestHandler):
def post(self):
fileinfo = self.request.files['filearg'][0]
fname = fileinfo['filename']
fh = open(__UPLOADS__ + fname, 'w')
fh.write(fileinfo['body'])
self.finish("Success!")
application = tornado.web.Application([
(r"/", Userform),
(r"/upload", Upload),
], debug=True)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Upvotes: 1
Views: 1057
Reputation: 36514
If the server is running on a Windows machine, it's because this line of code:
fh = open(__UPLOADS__ + fname, 'w')
opens the file as a text file. When you use that to create a file containing binary data, every occurrence of the value 0x0a
(newline) will be replaced with a \n\r
pair. Change that line to
fh = open(__UPLOADS__ + fname, 'wb')
...to open that as a binary file & see what happens.
Upvotes: 4