- [Instructor] As mentioned in the previous video,
we need a middleware that can handle multipart form data
and the module of choice for that is called multer.
Let's install it
by running npm install --save multer.
Now we have to require and set up multer.
I don't want to clutter my route with it,
so I will create a new file middlewares.js in routes.
So, down here in server, routes,
I create a new file, middlewares.js.
In there I will now require multer
and now we of course have to set it up.
So, I add const upload equals multer
and we can parametrize multer now with configuration
and they're about to limit the file size.
This is especially important
because we won't configure multer
to destroy the file on disk
and the default is storing it in memory.
Allowing unlimited file sizes here
could easily be used to create a denial-of-service attack.
So, for the limits I will now add
fileSize and this should be four megabytes.
Let's fix the indents really quick.
Now all that is left to do
is to export this configured multer instance,
so I add multer.exports.upload equals upload.
Now let's head over to our users, index.js file
with the routes in it
and there I simply add const middlewares
equals require
middlewares.
Next we have to modify the post route for the registration,
so I'm scrolling down
'til I find the post route in line 26
and there I will now add middlewares.upload
and there we set the upload.single,
so we want to accept the single file upload
and for that we also set the field name we are looking for,
the field is named avatar
and that's it.
Multer will give us the uploaded result
in request.files and the regular form fields
in request.body as before.
I will now use the debugger
to set a breakpoint
to see if this works as intended,
so I'm setting a breakpoint here in line 29
and I'm starting the debugger
and let's head over back to our website
and here I will fill out the form
and I select the file to be uploaded.
Let's submit.
And now you see that we hit this breakpoint.
Let's see which variables we have available,
so I click on Local and there I open request
and there I have to scroll down a little bit
and we see that we have the request body now again
with the regular form fields
and further down we now also have a file object
that contains a buffer with binary data
along with some metadata
to tell us more about the actually uploaded file.
So far so good.
In the next video, we will work on resizing
and storing this file.