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:
functionuploadFile(fileContent, fileName) {
// Encode the binary data to as base64.const data = {
fileContent: btoa(fileContent),
fileName: fileName
};
axios.post('http://localhost:8080/api/uploadFile', 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:
classUploadFileHandler(tornado.web.RequestHandler):
defpost(self):
requestBody = tornado.escape.json_decode(self.request.body)
# Decode binary content from base64
binary_data = base64.b64decode(requestBody[fileContent])
# Open file in binary modewithopen(requestBody["fileName"], "wb") as f:
f.write(binary_data)
Post a Comment for "Upload File As Json To Python Webserver"