首页 > 解决方案 > Flask FileField 显示完整路径

问题描述

我有一个有效的表格来上传图片

我想在设置图像后查看图像的完整路径(例如在我拥有0.jpeg但我想要的图片上/home/full_path/0.jpeg

代码的想法很简单 - 设置图像和有关此图像的数据。

在此处输入图像描述

class IntersectionForm(FlaskForm):
    """
    Form to create new intersection
    """
    name = StringField("Название", validators=[
        InputRequired(), Length(min=4, max=int(2 ** 25 / 2.))
    ])
    schema_file = FileField("Схема", validators=[
        FileRequired(),
        FileAllowed(["jpg", "png"], "Только изображения!")
    ])
    schema_scale = FloatField("Масштаб (пиксели в метре)")
    submit = SubmitField("Добавить")

    
    def populate_obj(self, obj: Intersection) -> None:
        """
        Populates the attributes of the passed `obj` with data from the form's
        fields.

        :note: This is a destructive operation; Any attribute with the same name
               as a field will be overridden. Use with caution.
        """

        if self.schema_file.data is not None:
            schema_img = decode_image(self.schema_file.data.read())
            schema_height, schema_width = schema_img.shape[:2]

            obj.schema_img = schema_img

        obj.schema_height = schema_height
        obj.schema_width = schema_width
        obj.schema_scale = self.schema_scale.data

    super().populate_obj(obj)

表单的html代码

<form method="post" class="form" enctype="multipart/form-data" role="form">
                {{ form.csrf_token() }}
                {% if inter_id is defined %}
                    {{ form.id }}
                {% endif %}
                {{ render_field(form.name) }}
                {{ render_field(form.schema_file) }}
                {{ render_field(form.schema_scale) }}
                {% if inter_id is defined %}
                    {% include "load-spinner.html" ignore missing %}
                {% endif %}
                <div class="inter-item mb-3">
                    <img id="schema_file_preview" src="{{ img or '' }}" alt="Предварительный просмотр" class="d-inline-block"
                        width="{{ img_w or 100 }}%" height="{{ img_h }}%">
                </div>
                <div class="d-inline-flex">
                    {{ render_field(form.submit, button_style="outline-primary") }}
                    {% if inter_id is defined %}
                        <a href="{{ url_for('inter.view', id=inter_id) }}" class="btn btn-outline-danger ml-1" role="button">Отмена</a>
                    {% else %}
                        <a href="{{ url_for('inter.index') }}" class="btn btn-outline-danger ml-1" role="button">Отмена</a>
                    {% endif %}
                </div>
            </form>

我在网上没有找到例子

标签: pythonflask

解决方案


推荐阅读