Store Image in Mysql datatabse using flask

时光毁灭记忆、已成空白 提交于 2020-01-24 01:03:33

问题


I'm trying to get this image from an html form and store it in the database. I'm not sure what I'm doing wrong. I want to be able to save the image in a blob field in the database. see my code.I'm using flask. The problem here is, I'm not able to store the image in the database.

   @app.route('/upload', methods=["POST"])
    def get_images():
        if request.method == "POST":
            file = request.files['imagename']
            file.save(file.filename)

            newFile = file.read()

            c, conn = connection()


            c.execute('''
                         INSERT INTO ImageTable( PHT_Image)
                         VALUES(%s)''',
                      [newFile1])
            conn.commit()

回答1:


I would strongly suggest saving file on disk and string path of that file into database. For eg:

APP_IMAGES = os.path.join(APP_ROOT, 'images/')

class RegistrationForm(Form):
    myImage = FileField('Choose Image file')

@app.route('/register/', methods=["GET","POST"])
def register_page():
    try:
        form = RegistrationForm(CombinedMultiDict((request.files, request.form)))
        filename = 'None'
        if request.method == "POST"):
            filename = secure_filename(form.avatar.data.filename)
            form.myImage.data.save(APP_IMAGES + filename)
            dbu = DatabaseUtility(db)
            dbu.RunCommand("INSERT INTO users (avatar) VALUES (%s)",thwart(filename)))
                dbu.Commit()
                dbu.Disconnect()
                flash("Done!")

    except Exception as e:
        return(str(e))


来源:https://stackoverflow.com/questions/48981784/store-image-in-mysql-datatabse-using-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!