I'm trying to create a function for uploading files from a web page (RequestHandler + HTML) with tornado.
I found a way to do it with this code. But the problem is that the whole content of the file is wrote in a single line which is normal because the function self.request.files saves the content of the file in a dictionary.
python code:
def post(self):
myfile = self.request.files['file1'][0]
print("myfile is", myfile)
fname = myfile['filename']
upload_file = open("./some_files/%s" % fname, 'w')
upload_file.write(str(myfile['body']))
html code:
<form enctype="multipart/form-data" action="/build" method="post">
File: <input type="file" name="file1" />
<br />
<br />
<input type="submit" value="upload" />
</form>
So how can I separate the lines of my uploaded file?
The problem was due to the fact that the content of the file was in binary format and I transformed it to string with str()
. The correct way was to use decode()
like this
def post(self):
myfile = self.request.files['file1'][0]
fname = myfile['filename']
file_content = myfile['body'].decode("utf-8")
print(file_content)
with open("./some_files/%s" % fname, 'w') as upload_file:
upload_file.write(file_content)