Python 如何使用 Flask WTF FileField 实际上传文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14589393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to actually upload a file using Flask WTF FileField
提问by Siecje
In my forms.py file I have I have
在我的 forms.py 文件中,我有
class myForm(Form):
fileName = FileField()
In my views.py file I have
在我的 views.py 文件中,我有
form = myForm()
if form.validate_on_submit():
fileName = secure_filename(form.fileName.file.filename)
In my .html file I have
在我的 .html 文件中,我有
{% block content %}
<form action="" method="post" name="simple" enctype="multipart/form-data">
<p>
Upload a file
{{form.fileName()}}
</p>
<p><input type="submit" value="Submit"></p>
</form>
{% endblock %}
and it seems to work when I hit submit but the file is not in any of the project directories.
当我点击提交时它似乎工作但文件不在任何项目目录中。
采纳答案by Siecje
I just had to call .save on form.fileName.file.save
我只需要在 form.fileName.file.save 上调用 .save
myFile = secure_filename(form.fileName.file.filename)
form.fileName.file.save(PATH+myFile)
回答by codegeek
Have you looked at this:
你看过这个:
http://flask.pocoo.org/docs/patterns/fileuploads/#uploading-files
http://flask.pocoo.org/docs/patterns/fileuploads/#uploading-files
You have to set a few configs such as UPLOAD_FOLDER etc. You also have to call the save() function which I don't see in your posted code for views.py.
您必须设置一些配置,例如 UPLOAD_FOLDER 等。您还必须调用 save() 函数,我在您发布的 views.py 代码中没有看到。
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
回答by Travis Cunningham
On form.fileName.file, call '.save'.
在 form.fileName.file 上,调用“.save”。
filename = secure_filename(form.fileName.file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
form.fileName.file.save(file_path)
Make sure to use secure_filename() to prevent users from putting in bad file names, such as "../../../../home/username/.bashrc".
确保使用 secure_filename() 来防止用户输入错误的文件名,例如“../../../../home/username/.bashrc”。
Using os.path.join will generate the correct absolute path no matter what OS you are on.
无论您使用什么操作系统,使用 os.path.join 都会生成正确的绝对路径。

