image.payload.read() 返回图像的原始数据,这是我们想要的,只是我们不想把它放在 IMG 标签的 src 属性中。
我们想要的是将原始图像数据作为图像提供,并将该图像的 URL 放入 src 属性。
Here is one example how it can be done with a temporary file.
这很可能是您想要的解决方案。
from tempfile import NamedTemporaryFile
from shutil import copyfileobj
tempFileObj = NamedTemporaryFile(mode='w+b',suffix='jpg')
copyfileobj(image.payload,tempFileObj)
tempFileObj.seek(0,0)
然后在视图中提供文件
from flask import send_file
@app.route('/path')
def view_method():
response = send_file(tempFileObj, as_attachment=False, attachment_filename='myfile.jpg')
return response
可能直接从 ImageGridFSProxy 对象发送图像数据并跳过临时文件,但我不确定。
---------
现在您已经完成了代码,我将按照我的方式发布。以及我试图解释的方式。 :)
这是我的 app.py。
from flask import Flask, send_file, render_template
import mongoengine as mo
app = Flask(__name__)
c = mo.connection.connect('localhost')
@app.route('/')
def index():
images = MyDoc.objects.all()
return render_template('template.html', images=images)
# Separate view for the images
@app.route('/image/<img_name>')
def image(img_name):
image = MyDoc.objects(file_name=img_name).first()
# This is where the tempfile stuff would have been if it would
# have been needed.
if image:
return send_file(image.payload, mimetype='image')
else:
return "404" # might want to return something real here too
class MyDoc(mo.Document):
file_name = mo.StringField(max_length=255, required=True)
payload = mo.ImageField(required=True)
if __name__ == "__main__":
app.run(debug=True)
这是模板。
<html>
<body>
<div>
This is a body!
<div>
{% if images %}
{% for image in images %}
{{ image.file_name }}
<img src="/image/{{ image.file_name }}" />
I'm an image!<br><br>
{% endfor %}
{% endif %}
</div>
</div>
</body>
</html>
整个tempfile 是不必要的,因为可以直接使用send_file 发送有效负载。需要 mimetype 来告诉浏览器“这是一个图像”,并且浏览器应该只显示它而不是下载它。这不是我之前怀疑的as_attachment。
这样就无需使用tempfile 保存文件或将文件保存到静态提供它们的目录中。