requestobject in a
uploadsdirectory in our repo to store files.
uploadsfolder, but ignore the files in it because the files in
uploadsare not part of application logic. Ignoring the files in
uploadsalso prevents our Git repo from getting unnecessarily large.
enctype="multipart/form-data"attribute to our opening
formtag. This signals that the form contains file data.
inputtag of type
fileto accept file data in the form.
multerUpload.singlemiddleware to the POST route where we plan to receive the file upload. Provide the file upload form input field's
nameattribute as a parameter to the middleware.
request.fileand 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.
photo. Please use a more descriptive name depending on your context.
imgtag in our EJS template. When the rendered HTML page loads client-side, it will make a request for the file via the
imgtag, and Express will serve the file.
express.staticconfig to allow Express to serve files from the
uploadsfolder. Express supports multiple
express.staticconfigs 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.
index.jsdoesn't need to change. Our SQL query now returns the uploaded file's name because we stored it in the
photocolumn in the
photoattribute of the recipe record to request the photo file in the
photocontains the file name stored in the database.