如何将上传的图片传递给Flask中的template.html [英] How to pass uploaded image to template.html in Flask

查看:182
本文介绍了如何将上传的图片传递给Flask中的template.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用烧瓶,并尝试使用快速入门教程做一些非常简单的事情,只是在我的机器(本地服务器)。我生成一个简单的上传表单,成功上传图像文件。然后,我想把这个图像作为一个变量传递给一个 template.html 来显示在页面中。 template.html 文件显示正常,但图像始终是断开的链接图像符号。我已经尝试了很多不同的路线,但我有一种感觉,我正在做的事情有点不对。

 从flask导入导入os 
烧瓶,请求,重定向,url_for,send_from_directory,
render_template

UPLOAD_FOLDER ='/ home / me / Desktop / projects / flask / uploads'
ALLOWED_EXTENSIONS = set(['txt','pdf','png','jpg','jpeg' ,'gif'])

app = Flask(__ name__)
app.config ['UPLOAD_FOLDER'] = UPLOAD_FOLDER
$ b $ def allowed_file(filename):
return'。'in filename and \
filename.rsplit('。',1)[1] ALLOWED_EXTENSIONS

app.route('/',methods = [ 'GET','POST'])
def upload_file():$ b $如果request.method =='POST':
file = request.files ['file']
如果file和allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config ['UPLOAD_FOLDER'],filename))
返回重定向(url_for('uploaded_file ',filename = filename))
return'''
<!doctype html>
< title>上载新档案< / title>
< h1>上载新档案< / h1>
< form action =method = post enctype = multipart / form-data>
< p><输入类型=文件名称=文件>
< input type = submit value =上传>
< / form>
'''

@ app.route('/ uploads /< filename>')
def uploaded_file(文件名):
filename ='http:/ /127.0.0.1:5000/uploads/'+ filename
return render_template('template.html',filename = filename)

if __name__ =='__main__':
app .run()

这是 template.html

 <!doctype html> 
< title>来自Flask的问候< / title>
{%if if filename%}
< h1>一些文字< img src ={{filename}}>更多文字!< / h1>
{%else%}
< h1>无论出于何种原因都没有图片< / h1>
{%endif%}

如何将上传的图片文件传递给 template.html 所以它会正确显示?

感谢

解决方案

现在发生的事情是 /uploads/foo.jpg 返回template.html中的HTML。在那里,你尝试使用 /uploads/foo.jpg 作为img标签的来源。让我们像这样修改它: /show/foo.jpg 返回HTML页面和 /uploads/foo.jpg 返回图片。用这两个替换后面的路线,你应该很好去:

  @ app.route('/ show /< filename>')
def uploaded_file(filename):
filename ='http://127.0.0.1:5000/uploads/'+ filename
return render_template('template.html',filename =文件名)

@ app.route('/ uploads /< filename>')
def send_file(filename):
return send_from_directory(UPLOAD_FOLDER,filename)


I am using flask, and trying to do something very simple using the quickstart tutorial, just running on my machine (local server). I produce a simple upload form which successfully uploads an image file. I then want to pass this image as a variable to a template.html for display within a page. The template.html file displays fine, but the image is always a broken link image symbol. I've tried a number of different paths, but I have a feeling I am doing things a bit wrong.

import os
from flask import Flask, request, redirect, url_for, send_from_directory, 
                  render_template

UPLOAD_FOLDER = '/home/me/Desktop/projects/flask/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    filename = 'http://127.0.0.1:5000/uploads/' + filename
    return render_template('template.html', filename = filename)

if __name__ == '__main__':
    app.run()

This is template.html:

<!doctype html>
<title>Hello from Flask</title>
{% if filename %}
  <h1>some text<img src="{{filename}}"> more text!</h1>
{% else %}
  <h1>no image for whatever reason</h1>
{% endif %}

How can I pass the uploaded image file to template.html so it will display correctly?

Thanks

解决方案

What's happening now is that /uploads/foo.jpg returns the HTML inside template.html. There you try to use /uploads/foo.jpg as the source of the img tag. Nowhere you serve the actual image out.

Let's modify it like this: /show/foo.jpg returns the HTML page and and /uploads/foo.jpg returns the image. Replace the latter route with these two and you should be good to go:

@app.route('/show/<filename>')
def uploaded_file(filename):
    filename = 'http://127.0.0.1:5000/uploads/' + filename
    return render_template('template.html', filename=filename)

@app.route('/uploads/<filename>')
def send_file(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)

这篇关于如何将上传的图片传递给Flask中的template.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆