0

I used flask SQLAlchemy to upload an image. after uploading the image it's stored in database but is not displaying in html browser. It seems to be okay. I don't find the solution. no error is displaying as well. In htlm browser, it's showing just a small photo icon. Nothing else.

main.py

app = Flask(__name__)
app.config["UPLOAD_PATH"] = "static/"

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
db = SQLAlchemy(model_class=Base)
db.init_app(app)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_PATH = os.path.join(APP_ROOT, 'uploads')

class Gallery(db.Model):
    __tablename__ = "gallery"
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    image: Mapped[str] = mapped_column(String(500))

class GalleryForm(FlaskForm):
    image = FileField('Add Gallery Photo', validators=[FileRequired(), FileAllowed(['jpg','png'], 'Images only!')])
    submit = SubmitField("Add Gallery Photo")

@app.route('/admin', methods=["GET", "POST"])
def index():
    gallery_form = GalleryForm()
    if gallery_form.validate_on_submit():
        new_gallery = Gallery()

        # Handling file upload
        uploaded_file = gallery_form.image.data
        filename = secure_filename(uploaded_file.filename)
        image_path = os.path.join(app.config['UPLOAD_PATH'], filename)
        uploaded_file.save(image_path)
        new_gallery.image = image_path
        path_list = new_gallery.image.split('/')[1:]
        new_path = '/'.join(path_list)

        new_gallery.image = new_path

        db.session.add(new_gallery)
        db.session.commit()
        return redirect(url_for('index'))

    gallery_image = db.session.execute(db.select(Gallery)).scalars().all()
    return render_template("index.html" all_gallery=gallery_image, gallery_form=gallery_form)

index File:
{% for photo in all_gallery %} 
    <img src="{{ photo.image }}">
{% endfor %}
3
  • Images should be stored as BLOB (Binary Large OBject), not String. Something like image: Mapped[str] = mapped_column(BLOB) should work. Commented Mar 27, 2024 at 3:16
  • Take a look at this answer: stackoverflow.com/a/29922509/4583620 Commented Mar 27, 2024 at 3:21
  • gallery_image = db.session.execute(db.select(Gallery)).scalars().all() for image in gallery_image: encoded_image = base64.b64encode(image.image).decode("utf-8") image.encoded_image = encoded_image HTML: {% for photo in all_gallery %} <div class="project"> <img class="smallImage image-block" src="data:image/jpeg;base64,{{ photo.image }}"> </div> {% endfor %} Its uploaded now. but not showing in HTML file Commented Mar 27, 2024 at 18:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.