express.urlencoded
middleware to populate request.body
. For file uploads, we will add a similar configuration to Express using the Multer library to accept binary file data in requests.request
object in a file
key.multer
uploads
directory in our repo to store files.uploads
to .gitignoreuploads
folder, but ignore the files in it because the files in uploads
are not part of application logic. Ignoring the files in uploads
also prevents our Git repo from getting unnecessarily large.enctype="multipart/form-data"
attribute to our opening form
tag. This signals that the form contains file data.input
tag of type file
to accept file data in the form.multerUpload.single
middleware to the POST route where we plan to receive the file upload. Provide the file upload form input field's name
attribute as a parameter to the middleware.request.file
request.file
and save it to the DB. Notice how the file name is a cryptographic hash, and there is no file extension. This is deliberate to ensure file names are unique. If we wish to name files differently Multer accepts configuration options at initialisation.request.file
photo
in the recipes
table.photo
. Please use a more descriptive name depending on your context.img
tag in our EJS template. When the rendered HTML page loads client-side, it will make a request for the file via the img
tag, and Express will serve the file.uploads
express.static
config to allow Express to serve files from the uploads
folder. Express supports multiple express.static
configs so we don't need to worry about conflicts with our other static file folders for files such as CSS.<UPLOADED_FILENAME>
references the Multer-generated filename, not the filename on our local computers.request.file
example above.index.js
doesn't need to change. Our SQL query now returns the uploaded file's name because we stored it in the photo
column in the recipes
table.photo
attribute of the recipe record to request the photo file in the uploads
folder. photo
contains the file name stored in the database.