3

我想从 request.form["file"] 写入文件,但我做不到。

我的contact.html 在这里。

客户端代码是这样的......

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

服务器端是这样的

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)

我想写这个是png文件到某处上传的文件。你有什么主意吗?

提前致谢。

4

2 回答 2

6

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/

于 2013-04-21T16:06:27.410 回答
1

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'))
于 2013-04-21T16:06:39.583 回答