0

can anyone help me to display an image or pdf file stored in mongodb with a flask app to the browser? Currently, when I try, I get a 200 response but the browser is just blank. This is the function I use:

My mongo document is modeled like this:

class Users(db.Document):
    _id = db.StringField()
    name = db.StringField()
    picture = db.ReferenceField('fs.files') #holds the reference for the file in the database
    upload_picture = db.FileField() #used to load pics via flask into the database
    email = db.StringField()
    password = db.StringField()
    meta = {'collection': 'Users'}

This is the function I had to retrieve and display the image. However with this function, I get a blank browser:

class RetrievePicture(Resource):
    def get(self, id):
        try:
            user = Users.objects(_id=id).first()
            doc = user.picture.read()
            return send_file(io.BytesIO(doc), mimetype='image/png')
        except Users.DoesNotExist:
            return 'Picture not found', 401

The flask route I enter into the browser is supposed to return the picture from the specific user whose id I enter. The route looks like this http://127.0.0.1:5000/api/picture/(id) Does anyone know what I'm doing wrong or have another solution using MongoEngine?

  • Seems you need `.seek(0)`. Take a [look](https://stackoverflow.com/a/45111660/3710490) – Valijon Mar 17 '20 at 07:26
  • @Valijon I'm getting this error `TypeError: a bytes-like object is required, not 'files'`. How do I read the file object and return a picture? Or I should ask, what can I use to translate the file object into a file that can be displayed? Thanks. – blazedtrailz Mar 18 '20 at 17:26

0 Answers0