19. File Upload In NestJS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello friends welcome back to this tutorial series this is the part 19 of this uh project and in this part we will be learning how we can upload a file in nest chess in the previous part we saw how to create a custom decorator and we created this custom decorator that's the user decorator here to get the currently logged in user and in our auth service if you remember we created not in the all service or controller we created a couple of endpoints one to verify the auth status and the other one to log out the user right so let me close all these files i don't need them i don't need the user decorator either so in the post controller uh first of all we need a route where we can uh send the request to upload the file so just below the slug endpoint i'm going to create a new post endpoint here okay because we'll be sending some data so post would be the best http verb here and the path will be upload slash photo you can give any path you like and this is the name i chose so here the function name again you can give any function name you want i'll give it upload auto and this function would essentially take a file okay so i'll use a decorator here this uploaded file and this is imported from the nest js common package i'll show you here uh uploaded file you see it's imported from nesjs common library and once you do that where is it where is my function oh there it is i'll give it a name in a name you want like file and the type of this file variable will be a little bit different it will be express dot malta dot file and you see it's giving me a red squiggly here so it's not found because uh let me check something wrong with the import statements oh let me check here again let's try it again express dot multa dot file express from express okay like that let's see i got it here and now let's try to use malta that file that's not taking right now let's head back to the official docs so here i'll search for mulder basic example okay the file type do you see the file type here yeah express dot melter dot file so do i need to import anything okay yeah i need to import the types here my bad so let's go here the terminal uh like do like that okay hopefully this error should go away uh yeah there you go it's gone now because now it knows what is malta and it is able to find the name space properly so i was missing this uh types for malta the in the dependencies make sure you install this okay so this is why it's always good to refer the official docs whenever you're stuck somewhere so once you do that let me minimize this i don't need it anymore so i gave this file the correct type now what we can do so we can simply console log the file here okay and still this will not uh be capable of uploading files because i'm not using multi as of now i'm simply defining defining an endpoint and the file here let's see if i try to hit this endpoint with a with an image file what do we get so i go back to my postman i already created one new request here so i'll go to the body go to form data and here i'll choose file and i'll give it any name uh let's say the key is file any name you want and from a desktop i'll select this warzone image and here and i hit send okay so it's a 201 created i'll check my console what do we get we get undefined because this file was lost in the in the transit because we we never were able to capture this file okay so to do that we have to use an interceptor here and this interceptor is already provided to us by ns and the multa package and the interceptor name is file interceptor okay so as you know this would intercept the request and do something in between so this file interceptor takes a field name so this is the field that you will use in your front end so here i'm using file so i'll choose file but in my actual repo i have used a different name so make sure you check this file or the field name property there and then it takes some local options so in this in this local options we can define where we want this uh files to be uploaded in which folder so i'll create a new folder at the project level here so here so i'll say uploads so it should be at the root here okay and in my storage property okay i can define disk storage okay okay i have to import it so import this from malta okay so all these packages come along with nest stairs out of the box okay this is pretty neat and helpful so inside the disk storage options you can define the destination in my case it will be uploads and this is from the root okay so dot slash uploads and then we have the file name you can define the file name let me just show you what what we can define you can define the file name and i'll not use the default method here so it gives me a lot of things i'll simply remove this so file name would be an arrow function of course so and in this parameter list i will be having a request actual file and the callback function so in this method or the body you can define a custom file name that you would like the uploaded file to have so in our case we'll generate a new file name because otherwise it will have default uh file name that is there in the uh in your local drive and if you upload the same file twice it would again have a conflict so what what we'll do we'll construct a name and that we will use the file object here or the file variable here so this has got certain properties so we'll use the original name property and we'll split it uh with a dot okay and this will give this will make it into an array okay of strings if i remove this oops i remove this you see this is an array of strings but i would only need the first part so my file name is warzone dot jpg so the file name will be warzone and from dot after dot it will by extension so file extension equals to the same thing here but with one here now another i'm defining the on a final variable new file name [Music] that will be name [Music] dot split and if there are any spaces so i'll remove the spaces and join them with underscore and then i'll give another underscore after the file name and then we'll use the date.now function so it will insert the current timestamp then i'll put a dot and then the file extension simple once that is done i'll run the callback and this callback takes two parameters error and the file name so i don't have any error i'll pass null and the file name is new file name perfect so once the file name is constructed i'll go back here and i can also use a file filter property here again this is too much so i will remove this i'll use the arrow function okay so file filter means that i will only allow certain types of files such as images i don't want the user to be to be uploading a word file or an excel file here so i will limit the use cases to only image files so here again it will take a request file and a callback so in the body that is check if the file dot original name dot match so this uh can take a regular expression okay so i'm gonna copy the regular expression from my nodes so this is not complex i'll explain it to you because this is the matcher statement so this says that after the dot it should be either jpg jp ej png or kif and this this is the end so if it ends with any one of these four values that is allowed and if it does not so i have a i have an exclamation mark here so it simply negates the condition or negates the output of this sorry uh if statement so if it's not matching then i would return a call back and i'll not pass on any file so i'm not throwing any error here for i on purpose because that would prevent the execution to the to this actual function uh but i'm simply passing the null value here and the error but i'm not passing any files okay so my file is false if this error is if this condition is false so then in the else statement or in the default statement i'll pass the error as null and the file okay oh sorry i'll not file the true so this this takes uh true or false okay this accept file parameter this is this is a boolean so once you want to do this and if everything is working fine you can save the changes check your console okay now if you go back to your postman plan and hit send let's see what we have we have the file now in the console as you can see the original name was warzone.jpg however the destination file name was broadzone underscore the timestamp.jpg and it got uploaded to this path and if i check the upload folder i should have a new file here this is just a new file okay isn't it wonderful and simple this is this i mean let's just js has made this a lot easier so if you use a regular node.js node.js and express application it would take a lot of time to build this functionality but you get this out of the box with less and this is simply amazing so uh we don't want to console log here actually we want to send this file to the front end user now we'll do a small check so if the file is not there that means we are not sending a valid extension here so this this would only happen if my extension doesn't match and i can show you that so if i remove this file and choose maybe this icon here okay and hit send it doesn't work and i'll i'll throw through the message here through the error message here i'll say return [Music] error or maybe throw a new bad request exception uh file is not an image okay and else if it's if it's an image we'll simply uh construct a response and this will have my file path file path is my actual location of the file so i'll create an endpoint localhost 5000 posts pictures i'll get an and find by the name pictures and then i'll pass in the file name there okay to fetch the uh file actual file and here i'll return response save now go back now i'm sending the icon file okay so i'll hit send says file is not an image it's a bad request but now if i go back and select the same wall zone here and hit send i get this path and if i click this link okay it says i cannot get the picture right now because there is no end point but let's keep it there and i go back to my controller i'll quickly create a get endpoint that is for the pictures pictures and this expects a file name okay so if i actual uh function name you can put any name you want i'll say get picture and this will have a i'll fetch the parameter using the param decorator and this will be file name and i'll get a local what you call local variable file name and i'll also use the response property from express so i'll simply respond dot send file method so this is this comes along with your along with this uh name space or interface okay so send file it takes three arguments okay first one is the file that you want to send that will be file name of the path and second one is the option okay so i'll define the root property here to upload so now if i send or save the changes okay i still have my browser open with this error now if i refresh this i should get the picture now right let's upload another one uh maybe this background okay hit send and i follow this link so i get this image so this pretty much concludes the file upload uh i mean while upload video and we saw how easy it is to create endpoint to upload the file and to fetch the file okay and it doesn't matter if the file names are same because it will be appended with the timestamp so it will never ever conflict with your previous uploads so i hope you like this particular video if you have any doubts any comments and suggestions put those in the comment section below and in the next video i plan to cover the user or role based access control system so please stay with me stick to this uh tutorial and don't forget to hit the like button the subscribe button and share it with your friends so till then enjoy the series and i'll see you in the next video take care and have a wonderful day
Info
Channel: Programming's Fun
Views: 8,439
Rating: undefined out of 5
Keywords: nestjs, angular, mysql, blog project, blog project angular, angular project, mean stack project, nestjs api, nest js api, express, nodejs, angular mean stack, bootstrap, primeng, nest cli, typeorm, typeorm integration, typeorm mysql, repository pattern, nest repository pattern, nest js repository pattern, event listeners, hooks, typeorm hooks, hooks in typeorm, nestjs blog, nest js blog, nestjs cms, nestjs cms blog, file upload, nest js file upload, multer file upload
Id: x6odoXBcerw
Channel Id: undefined
Length: 18min 50sec (1130 seconds)
Published: Mon Oct 25 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.