nobinobiru
nobinobiru

Reputation: 792

How to write png file to target directory from client side by flask

I want to write to file from request.form["file"] but I can't do it.

My contact.html is here.

Client side code is like this...

<form action="contact" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="submit">
</form>

Server side is like this

filestorage = request.files["file"]

print type(_file) #-> <FileStorage: u"__proto.png" ("img/png")>

# I tried below this , but it doesn't work.

f = open("tmp.png","wb")
f.write(filestorage)

I want to write this which is png file to uploaded file somewhere. Do you have any idea?

Thanks in advance.

Upvotes: 4

Views: 10103

Answers (2)

blob42
blob42

Reputation: 549

First, you have to configure your upload folder

app.config['UPLOAD_FOLDER'] = PATH_TO_UPLOAD_FOLDER

Then to save your file

f = request.files["file"]
f.save(os.path.join(app.config['UPLOAD_FOLDER'], 'tmp.png'))

Upvotes: 1

ubik
ubik

Reputation: 4560

You have the save() method of the FileStorage object, that lets you save the file content to disk:

file.save('/path/to/your/file')

Flask Documentation: http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.save

A useful tutorial: http://flask.pocoo.org/docs/patterns/fileuploads/

Upvotes: 7

Related Questions