【问题标题】:Python/Flask + WTForm - File upload not working, <input> field not picking upPython/Flask + WTForm - 文件上传不工作,<input> 字段不拾取
【发布时间】:2022-08-03 20:29:24
【问题描述】:

我在使用 Flask + WTF Forms 从本地文件系统上传文件时遇到问题。由于某种原因,浏览器似乎阻止我将文件加载到&lt;input/&gt; 字段中。事件未起。我什至收到这个消息。

<input> picker was blocked due to lack of user activation.

有趣的是,我记得几周前我正在测试它时这个工作。

这是我的 HTML + JS 的样子:

...

<div class=\"row\">
    <div class=\"col-lg-12\">
        <div class=\"file-input\">
            <input type=\"file\" class=\"nft1-file-collect\">
            <label for=\"signature\">{{signature}}</label>
            {{ form.signature(id_=\'signature\', onchange=\'showSignaturePreview(event)\') }}
            <span class=\"nft1-file-location\">Choose a File</span>
            <button type=\"button\" class=\"nft1-file-browse\">Browse</button>
            <span class=\"file-formate\">PNG Transparent, Max 150MB</span>

            <img id=\"signature_preview\" src=\"{{ url_for(\'static\', filename=\'images/docs/signature-generic.png\') }}\" style=\"display: block;margin-left: auto; margin-right: auto; height: 250px;\" alt=\"\"/>
        </div>
    </div>
</div>

...
function showSignaturePreview(event){
    if (event.target.files.length > 0){
        var src = URL.createObjectURL(event.target.files[0]);
        var preview = document.getElementById(\"signature_preview\")
        preview.src = src;
        preview.style.display = \"block\"
    }
}

这是form.py 的样子:

from flask_wtf.file import FileField, FileRequired
from flask_wtf import FlaskForm
from wtforms import Form, StringField, validators 
from wtforms.fields import DateField, IntegerField, HiddenField, SelectField
from wtforms.validators import DataRequired, InputRequired

class FileUploadForm(FlaskForm):
    name           = StringField(\'name\', render_kw={\'class\':\'input-text\'}, validators=[validators.data_required()])
    date_of_birth  = DateField(\'dob\', render_kw={\'class\':\'input-text\'}, validators=[validators.data_required()])
    signature      = FileField(\'signature\', render_kw={\'class\':\'nft1-file-collect\'}, validators=[validators.optional()])

任何帮助,将不胜感激!

  • 您是否检查过 JavaScript 控制台中是否有错误消息(在 DevTool 中)。您还可以使用console.log() 显示执行了哪部分代码以及变量中的内容的信息。如果你加载了一些 JavaScript 库,那么你应该检查DevTool 中的标签Network,看看加载这个库是否有问题。

标签: python flask


【解决方案1】:

出于某种原因,我需要将 Flask 更新到最新版本,因为我使用的是 Chrome 100+。我不知道为什么,但更新后一切正常。

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 2020-10-13
    • 2019-02-07
    • 1970-01-01
    • 2023-01-21
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    相关资源
    最近更新 更多