mysql: Saving files in mysql with nestjs

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.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.