Stream some documents (.zip, .txt, .pdf) and store them in the blob field in mysql

In web application, sometimes we need the user to upload the document, and store the document uploaded by the user, and then for the user to operate, there are two ways to achieve this operation.

1. After the user uploads the document, store the document under a certain path, and then store the path and the document name in the database

2. After the user uploads the document, perform binary reading (stream processing), and then store the read binary into the database

The method 2 is implemented below.
Environment: python, mysql

First we have to read the file

f = open('xxx.zip', 'rb')
data = f.read()

Then store the data in mysql

cxn = MySQLdb.connect(....)
cur = cxn.cursor()
sql = 'insert into table_name (...) values(...)'%MySQLdb.Binary(data)
cxn.commit()
cxn.close()

In this way, after the document is converted into a binary, it is stored in the mysql database, and the next time it is retrieved, only the retrieved data needs to be stored in a document.

Points to note:
1. In the environment of Python's own library (without other third-party libraries), it is not possible to convert pdf files.
2. In the database, remember to define this field as a binary field

If you need to convert pdf documents, you can use the Python library PyPDF

Published 190 original articles · 19 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/zengchenacmer/article/details/46898377