Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing file content in DB

I am making a model in which i have a FileField. I want to store the file content in a database column, instead of file path. Any suggestions?

like image 375
ha22109 Avatar asked Jul 03 '09 11:07

ha22109


People also ask

How file contents are stored in database?

If you want to have full control over your content, put the files in a blob field in the database. I generally also keep the filename in a separate field, so I can reconstruct the file as necessary (that way you keep the extension, which ties it to a file type in most operating systems).

Can you store text files in a database?

Yes you can, but you would probably be better off storing them on the file system and storing a path to the file in the DB.

Can I store files in SQL database?

SQL Server already has the FILESTREAM feature. The FILESTREAM feature provides efficient storage, management, and streaming of unstructured data stored as files on the file system.


2 Answers

Disregard the naysayers. If you want to have full control over your content, put the files in a blob field in the database. I generally also keep the filename in a separate field, so I can reconstruct the file as necessary (that way you keep the extension, which ties it to a file type in most operating systems).

Be sure to store the actual blob data in a separate table, only connected to your filename / extra info table via an id ... that way you don't sacrifice any performance when dealing with any information related to the file other than the content itself.

What the naysayers fail to realize, is that databases are simply an extremely optimized form of file system. Bytes are bytes and disc sectors are disc sectors. Databases are simply much better at organizing and searching those bytes than file systems are. Not to mention, databases implement much more stringent security than most file systems and are better maintained (with backups, support staff etc.).

like image 94
Ron Savage Avatar answered Sep 28 '22 07:09

Ron Savage


I know this is an old question, but there's been some good code written since then to allow this option. Specially, see django-database-files, which will use Django's storage API to make all FileFields and ImageFields store their contents in the database. There's also a fork to cache the files locally on the filesystem, to overcome the biggest caveat of using the database, which is latency.

like image 26
Cerin Avatar answered Sep 28 '22 06:09

Cerin