First of all I don't recommend saving files in mysql or any other database. However, if you have any difficulty in saving elsewhere, I present an option below.
did not know the nestjs until a few weeks ago however in those 3 weeks I developed my knowledge and learned a lot about nestjs. Which is a framework built on top of express. which reminds me a lot of angular in some cases.
Why save files in Mysql?
There is no right or wrong reason to save files in mysql but it is recommended to save to the file system on the server. However, there are other dedicated servers to save files like firebase storage or Amazon S3.
In my case I started saving files in mysql because the hosting server doesn't support files. With that saving files in the database can be a solution to this problem if you have a similar one.
Example upload files to mysql
Below are some example scripts on how to save data in the database, however in my example I used 3 fields in a table. You can customize it to your liking, remember that it is important to bring the content-type and filename for the Download.
At first I was going to use base64 to save the data from the files, but researching to find out that mysql has the binary type, it was enough to save the binary in bd.
file upload
If you are a beginner and are testing this solution to save files in mysql do not forget to upload the file with multipart/form-data in the enctype attribute.
If you need to send via axes or some lib front client you need to pass the content-type: multipart/form-data and the files must be sent through the class FormData.
sample tamplate repository
Below is the link to the repository where you can download and test the sample files seen earlier.
Is it recommended to save files in MySQL?
This is not a recommended practice. It is best to save files to the server's file system or use dedicated storage services like Firebase Storage or Amazon S3. MySQL and other databases are not optimized for storing files and may present performance issues.
What important information should be stored in MySQL when saving a file?
To ensure that the file is downloaded correctly, it is crucial to store the content-type and file name along with the binary data. This information allows the system to identify the file type and present it to the user appropriately.
How to upload files to MySQL using NestJS and Axios?
When uploading files via HTML form, use the enctype=”multipart/form-data” attribute. On the frontend, use the FormData class to upload files via Axios, setting the content-type to multipart/form-data. On the backend (NestJS), use libraries like multer to process the upload and save the data to MySQL.
