snigcode
snigcode

Reputation: 395

Is there a way to add uploaded image into the database and retrieve it for display in another html page?

I am developing a flask web application currently. However, I do not know how I can get the uploaded images from the user into the SQLite database and retrieve it for later use (such as display it on the homepage and other pages).

I am very new to web development so I am not familar with many programming languages yet. I have seen other pages talking about the use of php, may I know if that is really needed? Are there other ways of doing so in flask?

Would appreciate it if someone is able to guide me.

Thank you!

Upvotes: 1

Views: 155

Answers (1)

Tohmaxxx
Tohmaxxx

Reputation: 434

You can base64 encode an image and use a data: url

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

if you simple paste

data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==

in your address bar, you will see a small red dot

In an app this looks like this:


# FLASK_APP=mini_app flask run
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
    __tablename__ = "Users"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    image = db.Column(db.String)


def create_app(config_filename=None, host="localhost"):
    app = Flask("demo_app")
    app.config.update(SQLALCHEMY_DATABASE_URI="sqlite://")
    db.init_app(app)
    with app.app_context():
        db.create_all()
        user = User(name="test", image="iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==")
        db.session.add(user)
        db.session.commit()
    return app

host = "0.0.0.0"
app = create_app(host=host)

@app.route("/image/<string:user_name>")
def show_profile(user_name):
    user = User.query.filter(User.name==user_name).one_or_none()
    if user:
        return f'User: {user.name}<br/>Pic:<img src="data:image/png;base64, {user.image}"/>'
    return "Not Found", 404


if __name__ == "__main__":
    app.run(host=host)

then go to http://localhost:5000/image/test

Upvotes: 2

Related Questions