我似乎无法弄清楚为什么一个字段在另一个字段成功上传文件时失败。我可以上传一张照片就好......但是当谈到pdf时,我无法通过验证。我已经搜索了我的代码,但是找不到任何东西。有趣的是,我可以通过手动上传设备上传照片,这对我来说没有意义。我猜想有什么东西与我如何使用flask-uploads配置flask-wtf有关,但是看到因为没有关于如何将两者一起使用的在线文档,我只是要尽我所能。
任何帮助都会受到赞赏,因为我需要上传pdf,这让我很难过。
代码如下......非常感谢!
config.py
UPLOADED_MANUALS_DEST = "C:/pyprojects/cc/uploads/eq_manuals/"
UPLOADED_MANUALS_ALLOW = 'pdf'
UPLOADED_PHOTOS_DEST = "C:/pyprojects/cc/uploads/eq_photos/"
UPLOADED_PHOTOS_ALLOW = 'png, jpg, jpeg'
__初始化__。PY
from flaskext.uploads import UploadSet, configure_uploads, patch_request_class
photos = UploadSet('photos')
manuals = UploadSet('manuals')
configure_uploads(app, (photos, manuals))
patch_request_class(app)
forms.py
class EQForm(Form):
name = StringField('Name', validators=[Required('Equipment Name is required.')])
photo = FileField('Equipment Photo', validators=[
FileAllowed(photos, 'Photo must be a png, jpg, or jpeg!')])
manual = FileField('Equipment Manual', validators=[
FileAllowed(manuals, 'Manual must be a pdf!')])
views.py
@app.route('/admin/equipment/', methods=['GET', 'POST'])
@roles_accepted('admin')
def equipment():
eqform = EQForm()
if eqform.validate_on_submit():
# os.path.join() the secured filename and the root path from config.py imported as join()
new_eq = Equipment(name = eqform.name.data)
if eqform.photo.data:
photo_path = join(
app.config['UPLOADED_PHOTOS_DEST'],
secure_filename(eqform.photo.data.filename)
)
eqform.photo.data.save(photo_path)
new_eq.photo_path = photo_path
if eqform.manual.data:
manual_path = join(
app.config['UPLOADED_MANUALS_DEST'],
secure_filename(eqform.manual.data.filename)
)
eqform.manual.data.save(manual_path)
new_eq.manual_path = manual_path
db.session.add(new_eq)
db.session.commit()
equipment = Equipment.query.all()
return render_template('equipment.html',
title="Equipment Database",
equipment = equipment,
eqform = eqform
)
equipment.html
<form action="" method="POST" enctype="multipart/form-data" class="eq-field hide" name="eqform">
{{ eqform.hidden_tag() }}
<ul class="list-group">
<li class="list-group-item">
{{ eqform.name.label }}: {{ eqform.name }}
</li>
<li class="list-group-item">
{{ eqform.photo.label }}: {{ eqform.photo }} <br>
<span style="font-size:.75em;">Photo must be a png, jpg, or jpeg.</span>
</li>
<li class="list-group-item">
{{ eqform.manual.label }}: {{ eqform.manual }} <br>
<span style="font-size:.75em;">Manual must be a pdf.</span>
</li>
</ul>
<input type="submit" class="btn btn-default" value="Submit">
</form>
答案 0 :(得分:0)
我犯了一个愚蠢的错误:
UPLOADED_MANUALS_ALLOW = 'pdf'
UPLOADED_PHOTOS_ALLOW = 'png, jpg, jpeg'
这两个我已声明为字符串的允许扩展名列表......将其更改为:
UPLOADED_MANUALS_ALLOW = ('pdf')
UPLOADED_PHOTOS_ALLOW = ('png', 'jpg', 'jpeg')
然而,有趣的是:列表仍然无法使用单个项目,所以我不得不添加两个:
UPLOADED_MANUALS_ALLOW =('pdf','PDF')