【问题标题】:Write file from BLOB mysql python从BLOB mysql python写入文件
【发布时间】:2012-09-01 04:57:17
【问题描述】:

我正在尝试从数据库中获取文件并将其写入磁盘。该文件存储为 BLOB。

现在我有以下代码:

#!/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])

任何帮助将不胜感激。谢谢:)

我调试了,它获取文件并将其写入磁盘,但是当我打开它时显示错误提示:

Not a JPEG file: starts with 0x2f 0x39

【问题讨论】:

    标签: python mysql file blob


    【解决方案1】:

    我找到了解决方案,我需要使用 decode('base64') ...这是一个简单的问题:/

    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()
    

    【讨论】:

      猜你喜欢
      • 2011-03-23
      • 2018-12-28
      • 1970-01-01
      • 2014-09-09
      • 2019-05-14
      • 2013-08-02
      • 2018-08-13
      • 2017-01-16
      • 2015-01-09
      相关资源
      最近更新 更多