2

I'm trying to get a file from a database and write it to disk. The file is stored as BLOB.

Now I have the following code:

#!/usr/bin/python
import MySQLdb

db2 = MySQLdb.connect(host="localhost",
                      user="root",
                      passwd="root",
                      db="digit")

cur = db2.cursor()
#get the name of the file
cur.execute("SELECT Name FROM ContentFiles WHERE ID=3")
nombre = cur.fetchone()
#open file and write into.
with open(nombre[0],"wb") as output_file:
    cur.execute("SELECT File FROM ContentFiles WHERE ID=3")
    ablob = cur.fetchone()
    output_file.write(ablob[0])

Any help would be appreciated. Thanks :)

I debugged and it gets the file and write it into disk, but when I open it shows an error saying:

Not a JPEG file: starts with 0x2f 0x39

1 Answer 1

5

I found the solution, I needed to use the decode('base64') ... it was an easy problem :/

cur = db2.cursor()
#get the file
cur.execute("SELECT mimetype,File,Name FROM ContentFiles WHERE ContentID=10414")
archivo = cur.fetchone()

imagen = open(archivo[2],'wb')
imagen.write(archivo[1].decode('base64'))
imagen.close()
Sign up to request clarification or add additional context in comments.

Comments

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.