[英]Why is if request.method == 'POST' and 'photo' in request.files
I have this little example script. 我有这个小例子脚本。 It gets a file from a HTML an uploads it to the server. 它从HTML获取文件,然后将其上传到服务器。 That part works just fine. 那部分工作正常。 Please see the script below. 请参见下面的脚本。
I would like to take some action if no file is selected in the form. 如果表单中没有选择文件,我想采取一些措施。 I thought the following would evaluate to false if no file was selected in the HTML form, but it seams to be always true. 我认为如果在HTML表单中未选择任何文件,则以下内容将评估为false,但它始终是true。
if request.method == 'POST' and 'photo' in request.files:
Either a file is selected or not 'Text to print' is returned. 选择文件还是不返回“要打印的文本”。
What am I missing here? 我在这里想念什么?
Any hint is appreciated. 任何提示表示赞赏。
Best regards Kresten 最好的问候克里斯滕
from flask import Flask, render_template, request
from flask_uploads import UploadSet, configure_uploads, IMAGES
app = Flask(__name__)
photos = UploadSet('photos', IMAGES)
app.config['UPLOADED_PHOTOS_DEST'] = 'static'
configure_uploads(app, photos)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.url(request.files['photo'])
fil = request.files['photo']
return 'Text to print'
return render_template('upload.html')
if __name__ == '__main__':
app.run(debug=True)
app.run(host='0.0.0.0')
The HTML template: HTML模板:
<html>
<head>
<title>Upload</title>
</head>
<body>
<form method=POST enctype=multipart/form-data action="{{ url_for('upload') }}">
<input type=file name=photo>
<input type="submit">
</form>
</body>
</html>
(Thanks to Danila for saving my day) (感谢达妮拉挽救我的生活)
In your case photo
always will be in request.files
, but filename
not(can be empty string). 在您的情况下, photo
始终位于request.files
,但filename
不存在(可以为空字符串)。 Just change condition to: 只需将条件更改为:
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and request.files['photo'].filename:
filename = photos.url(request.files['photo'])
fil = request.files['photo']
return 'Text to print'
return render_template('upload.html')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.