Skip to content Skip to sidebar Skip to footer

Upload File As JSON To Python Webserver

I want to upload a file as JSON from the client to a Python webserver (Tornado) and save it on the server. This is my simplified setup: Client HTML: , JSON.stringify(data)); }

On the server side, you need to deserialise from JSON, decode the base64 and the open a file in binary mode to ensure that what you are writing to disk is the uploaded binary data. Opening the file in text mode requires that the data be encoded before writing to disk, and this encoding step will corrupt binary data.

Something like this ought to work:

class UploadFileHandler(tornado.web.RequestHandler):

    def post(self):
        requestBody = tornado.escape.json_decode(self.request.body)
        # Decode binary content from base64
        binary_data = base64.b64decode(requestBody[fileContent])
        # Open file in binary mode
        with open(requestBody["fileName"], "wb") as f:
            f.write(binary_data)

Post a Comment for "Upload File As JSON To Python Webserver"