问题
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