首页 > 解决方案 > 从 html 表单中获取图像的 Python 问题

问题描述

想要从 HTML 表单到 python 脚本的图像我怎么能这样做,views.py 是我的 python 脚本。

<html>

<head>
  <title>Untitled Document</title>
</head>

<body>
  <form action="views.py" method="post" enctype="multipart/form-data">
    Image:
    <input type="file" name="image" accept="image/*" id="image" required>
    <input type="submit" name="submit" value="submit" required>
  </form>
</body>

</html>

标签: python

解决方案


您必须从 html 上传文件并保存在特定文件夹中。然后您可以再次从views.py 中使用该图像。

yourUploadImage.html

<html>

<head>
  <title>Untitled Document</title>
</head>

<body>
  <form action="views.py" method="post" enctype="multipart/form-data">
    Image:
    <input type="file" name="image" accept="image/*" id="image" required>
    <input type="submit" name="submit" value="submit" required>
  </form>
</body>

</html>

路线.py:

@app.route("/imagesubmit", methods=['GET', 'POST'])
def imagesubmit():
    if request.form.get('submit') == 'submit':
        f = request.files['image']
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('viewimage'))
    return render_template('yourUploadImage.html', form=form )

查看 :

路线.py

@app.route("/viewimage", methods=['GET', 'POST'])
def viewimage():
    myimage = fnmatch.filter(os.listdir(os.path.join(app.static_folder, "img")))
    return render_template('viewImage.html', item=item, myimage=myimage )

查看图片.html

{% for photo in myimage %}
    <a target="_blank" href="{{ url_for('static' , filename='img/' + photo) }}"><img src="{{ url_for('static' , filename='img/' + photo) }}" class="img-rounded" alt="Cinque Terre" width="304" height="236" ></a>
{% endfor %}

在 config.py 中:

import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
    UPLOAD_FOLDER = os.getcwd() + '/app/static/img/'

你可能需要稍微改变一下。但是逻辑是一样的。将图像保存在文件夹中并从那里提取以供查看。


推荐阅读