I've used two ways of uploading files
- only directly to folder
- directly into database from a folder
Upload to a folder
You can choose the folder of your choice to receive uploaded files, here in my project when a file is uploaded the file is taken , sperated by extension, rename the file to current timestamp and upload the file to folder and the name to the database. The file is only saved in the folder.
app = Flask(__name__, static_folder='uploads')
So the file into the folder and the name to the database.
Upload to database from a folder
So if you wanna a directly upload any file to the database, you need to save it as BLOB
.
File size by MySQL type:
TINYBLOB 255 bytes = 0.000255 Mb
BLOB 65535 bytes = 0.0655 Mb
MEDIUMBLOB 16777215 bytes = 16.78 Mb
LONGBLOB 4294967295 bytes = 4294.97 Mb =4.295 G
So basically you'd have to convert the file into binary form and then upload it to the database.
def convertToBinaryData(filename):
with open(filename, 'rb') as file:
binaryData = file.read()
return binaryData
Eventhough we are saving the file directly into the database we are forced to assign a location of file upload as same as the previous method. If you don't, flask will throw a error such as No such filename as filename.type
.
So we follow the same steps as before,and we add a step in converting the uploaded file to binary and upload the file and the file's name to the database.
You can delete the file from the folder after upload to the database if you want to.
Please check if the upload works!!
Here's the view of the BLOB
file and their names in the mysql database
Give it a shot and enjoy!! THANKS!
Project Installation
Requirements
- Python
3.10.6
Install
- clone
git clone https://github.com/pj8912/flask-file-upload.git
Create
virtual environment
and activateInstall requirements
pip install -r requirements.txt
Configuration
I used
mysql
database for this projectcreate an
.env
and add appropiate values for your mysql setup-
.env
variables :DB_HOST=
DB_USERNAME=
DB_PWD=
DB_NAME=file-test
Host, username, password and database name
My database name is file-test
- SQL file
Import sql file from mysql/file-test.sql
Run
python app.py
Top comments (3)
How to upload the file to the created SQL database?
If you want to directly store in database create a column with
BLOB
typeFile size by MySQL type:
TINYBLOB
255 bytes =0.000255 Mb
BLOB
65535 bytes =0.0655 Mb
MEDIUMBLOB
16777215 bytes =16.78 Mb
LONGBLOB
4294967295 bytes = 4294.97 Mb =4.295 G
updated it...