如何在页面上渲染来自Flask的图像?

2024-04-25 11:41:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的网站上渲染图像,但它不起作用(我只看到损坏的文件图标)。你能告诉我我做错了什么吗?在

上传图片的方式:

@app.route('/UploadImages')
def UploadImages():
    return render_template('UploadImages.html')


@app.route('/uploadImages', methods=['POST'])
def uploadImages():
    name = current_user.USERNAME
    file = request.files['inputFile']
    newFile=IMAGES(
        NAME=file.filename,
        USERNAME=name,
        DATA=file.read()
    )
    db.session.add(newFile)
    db.session.commit()

    return 'Saved ' + file.filename + 'to the database !'

这是我的数据库表:

^{pr2}$

我确信文件上载正确,因为当我使用:

@app.route('/download')
def download():
    file_data = IMAGES.query.filter_by(USERNAME='test1').first()

    return send_file(BytesIO(file_data.DATA),
attachment_filename='test.jpg',as_attachment=True) 

我得到的图像没有损坏。在

如何尝试渲染文件:

@app.route('/image')
def image():
    file_data = IMAGES.query.filter_by(USERNAME='test1').first()
    image = b64encode(file_data.DATA)
    return render_template('Image.html',data=list,image=image)

在网站上:

<img src="data:;b64encode,{{ image }}"/>

Tags: 文件图像imageappdatareturn网站def
2条回答

<img>数据URI应该是data:;base64,{{ image }},而不是{}。在

正如我在上面读到的,@Szymo给出的解决方案是最合适的。在

在你的主要路线上做这些事情

@app.route('/image')
def image():
    file_data = IMAGES.query.filter_by(USERNAME='test1').first()
    image = base64.b64encode(file_data.DATA).decode('ascii')
    return 
render_template('Image.html',data=list,image=image)`

并在html文件中编写以下代码:

^{pr2}$

相关问题 更多 >