提供存储在 SQLAlchemy LargeBinary 列中的图像 [英] Serve image stored in SQLAlchemy LargeBinary column

查看:20
本文介绍了提供存储在 SQLAlchemy LargeBinary 列中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传一个文件并将其存储在数据库中.我创建了一个 LargeBinary 列.

I want to upload a file and store it in the database. I created a LargeBinary column.

logo = db.Column(db.LargeBinary)

我读取上传的文件并将其存储在数据库中.

I read the uploaded file and store it in the database.

files = request.files.getlist('file')

if files:
    event.logo = files[0].file.read()

这是将图像作为二进制存储在数据库中的正确方法吗?如何将二进制数据再次转换成图像显示?

Is this the proper way to store an image as binary in the database? How do I convert the binary data into an image again to display it?

推荐答案

如果您绝对需要将图像存储在数据库中,那么是的,这是正确的.通常,文件存储在文件系统中,而路径存储在数据库中.这是更好的解决方案,因为 Web 服务器通常具有从文件系统提供文件的有效方法,而不是应用程序动态发送大量数据.

If you absolutely need to store the image in the database, then yes, this is correct. Typically, files are stored in the filesystem and the path is stored in the database. This is the better solution because the web server typically has an efficient method of serving files from the filesystem, as opposed to the application sending large blobs of data dynamically.

为了提供图像,编写一个获取图像数据并将其作为响应发送的视图.

To serve the image, write a view that gets the image data and sends it as a response.

@app.route('/event/<int:id>/logo')
def event_logo(id):
    event = Event.query.get_or_404(id)
    return app.response_class(event.logo, mimetype='application/octet-stream')

<img src="{{ url_for('event_logo', id=event.id }}"/>

最好使用正确的 mimetype 而不是 application/octet-stream.

Preferably serve it using the correct mimetype rather than application/octet-stream.

您还可以使用数据 uri 将图像数据直接嵌入到 html 中.这是次优的,因为每次呈现页面时都会发送数据 uri,而客户端可以缓存图像文件.

You could also embed the image data directly in the html using a data uri. This is sub-optimal, because data uris are sent every time the page is rendered, while an image file can be cached by the client.

from base64 import b64encode

@app.route('/event/<int:id>/logo')
def event_logo(id):
    event = Event.query.get_or_404(id)
    image = b64encode(event.logo)
    return render_template('event.html', event=event, logo=image)

<p>{{ obj.x }}<br/>
{{ obj.y }}</p>
<img src="data:;base64,{{ logo }}"/>

这篇关于提供存储在 SQLAlchemy LargeBinary 列中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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