问题
I'm trying to render image on my website but it's doesn't work (i see only corrupted file icon). Could You please tell me what i'm doing wrong ?
The way how I upload the image:
@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 !'
Here is my db table:
class IMAGES(db.Model):
ID = db.Column(db.Integer,primary_key=True)
NAME = db.Column(db.String(300),unique=True)
DATA = db.Column(db.BLOB)
USERNAME = db.Column(db.String(15))
I'm sure that the file is upload correctly because when I use:
@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)
I get the image not corrupted.
How I try to render the file:
@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)
and on the website:
<img src="data:;b64encode,{{ image }}"/>
回答1:
The <img>
data URI should be data:;base64,{{ image }}
and not data:;b64encode,{{ image }}
.
回答2:
As i have read this above the solution given by @Szymo n is the appropriate one for this.
In your main route do these things`
@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)`
And in html file write the following code:
<img src="data:;base64,{{ image }}"/>
来源:https://stackoverflow.com/questions/44861182/how-to-render-image-from-flask-sqlalchemy-on-page