我是Flask的新手。我想创建一个非常基本的站点,允许上传图像。我找到了手册,但我想让它略有不同。这是我的代码:
###main.py
import os
from forms import UploadForm
from flask import Flask,render_template, url_for, redirect, send_from_directory
from werkzeug import secure_filename
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
app = Flask(__name__)
app.config['SECRET_KEY'] = 'string'
@app.route('/', methods=('GET', 'POST'))
def upload():
form = UploadForm()
if form.validate_on_submit() and allowed_file(form.presentation.File.filename):
filename = secure_filename(form.presentation.file.filename)
print filename
form.presentation.File.save(os.path.join('C:\Users\user\Desktop\New', filename))
return redirect(url_for('/'))
filename = None
return render_template('upload.html', form=form, filename=filename)
if __name__ == '__main__':
app.run(debug=True)
### forms.py
from flask.ext.wtf import Form
from wtforms import FileField, validators, ValidationError, SubmitField
from wtforms.validators import InputRequired
class UploadForm(Form):
presentation = FileField('Upload Image here', validators=[InputRequired()])
submit = SubmitField("Send")
### upload.html
{% for message in form.presentation.errors %}
<div class="flash">{{ message }}</div>
{% endfor %}
<form action="/" method="POST" enctype="multipart/form-data">
{{ form.presentation.label }}
{{ form.presentation }}
{{ form.csrf_token }}
{{ form.submit}}
</form>
执行时我收到错误:AttributeError:&#39; FileField&#39;对象没有属性&#39;文件&#39; 我整天都在搜索,但我找不到答案的错误。
答案 0 :(得分:2)
根据wtforms doc,FileField没有“正确的文件”属性。
以下是文档示例:
class UploadForm(Form):
image = FileField(u'Image File', [validators.regexp(u'^[^/\\]\.jpg$')])
description = TextAreaField(u'Image Description')
def validate_image(form, field):
if field.data:
field.data = re.sub(r'[^a-z0-9_.-]', '_', field.data)
def upload(request):
form = UploadForm(request.POST)
if form.image.data:
image_data = request.FILES[form.image.name].read()
open(os.path.join(UPLOAD_PATH, form.image.data), 'w').write(image_data)
正如您所见,该文件是从request.FILE
而非FileField
读取的。 FileField
仅包含name
和data
属性。