1

I am trying to preview an image to be uploaded. I am using an upload form shown here

class Upload_Form(Form):
     date = DateField('Date on Certificate', validators =...)
     image = FileField(validators=[DataRequired()])

All that is really important for this is the image FileField. Here is the associated html with the upload. It extends a base html

{% block content %}
    <form action="" method="POST" name="upload" enctype="...">
    <p>{{ form.image.label }}<br>{{ form.image }}</p>
    ...
{% endblock %}

I need to either use python flask to preview the image or find a way to pull the URL from the file in the FileField to display the image with JS. I have tried form.image.url but that just returns an empty string. I know how to do this in JavaScript but I am having trouble understanding how to get it to be stored in the database since I am using a Python flask framework and it needs to be passed in the FileField from the class Upload_Form. I'm just having a hard time translating this to python flask as opposed to JS. Here is where I extract the file in flask.

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    form = Upload_Form()
    if request.method == "POST" and form.validate_on_submit():
        if img and os.path.splitext(img.filename)[1] in ALLOWED_EXTENSIONS:
            try:
                div_id = Division.query.filter_by(category=form.category.data).first().id
            except AttributeError:
                div_id = None
            c = Certificate(div_id=div_id,user_id=g.user.id, status=False)
            db.session.add(c)
            db.session.commit()
            ...
            return render_template('upload.html', title='Upload successful', form=form)
jamesmr13
  • 11
  • 4
  • 2
    Related: [Show image preview before upload](http://stackoverflow.com/questions/14069421/show-an-image-preview-before-upload) – Monkpit Oct 07 '15 at 21:00

0 Answers0