File Upload Using React And Express

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there I'm rajat in today's video we are going to learn about how to upload a file using react and express because this is a really practical problem which you might be required to solve as a web developer so let's dive right into it if you think that videos like this are something you would like to see in the future as well also give this video a thumbs up and consider subscribing before I start this video I have a disclaimer that I am not going to teach you the basics of react and Express in this video for all of those things I have recorded courses that are freely available on this channel so I request you to go back and watch those courses before diving into this tutorial because we will get our hands dirty and we will not deal with the basic stuff we will get straight to the point and before we dive into the code we should first understand how we are going to tackle this problem so I will grab my pencil and draw a simple diagram so as to illustrate what we are going to do in this video so we have to create two applications the first one is going to to be a react application and we are going to build this application using Create react app or also known as CRA so this is going to be our front-end application then we are going to have another application we will call it backend and this will be built using node so this one is going to be called front end in the repo which we are going to create and this one is going to be called back end okay so on this front-end application you are going to have a form on the landing page and this form is going to have an input button which is of file type so that a user can select a file to upload once the user has selected this file and submitted the form this request will go to our backend which is powered by node so here we will install express.js so that we can create a long running server or a web server I should say and in this web server we will upload a package called Express file upload now this package will help us in getting this data from the request so what this packet does is that it populates rack dot files so in this particular object we will get our binary data which will contain the actual file then we can use the utility method from Express File upload to move this file to somewhere else like let's suppose we want to move this file to the asset folder we can do that using the built-in functionality that comes with this Express File upload package okay so we will host our application on a route called profile so let's suppose here we are creating a functionality where a user can upload his or her after right so he will submit the Avatar then it will come to the profile route and in this profile route we will Mount this Express File upload plugin and then we can obtain the uploaded file using rack dot files and then we can save it elsewhere whatever we want to now let's get back to the computer and start writing out some code so we will start with a blank terminal and you are required to create a directory so I will first of all Zoom it a little bit and we are going to create a directory let's call it file upload okay this thing exists so let's call it file upload react okay go inside this folder and create a new react application you can use a command like create react app and then the name of your application so as we have decided that we are going to call it front end so we are going to name our application front end it will take some time so our application is ready to go we can open this thing up in vs code so that we can have a look at the code base so we have got our front-end folder I am going to open a terminal over here and what I will do I will go inside this front-end folder and start the application you can press Ctrl P to invoke the inbuilt functionality and then you can search for package.json which is going to reside inside this front end folder and from this you can have a look at what scripts are there for you to use so we have got to start so we will use npm Run start to start our application after a while you will see that it will start a new browser session and your application will be live in all its Glory now what we have to do we have to get rid of all the non-required code which comes pre-built with this application so what we are going to do we are going to go to the SRC folder inside app.js we are going to get rid of all of these things we do not need this thing for this application okay and it will be reloaded so as you can see we are getting to see a blank page now here we are going to create our form so we are going to create an empty form and inside this form we are going to have an input button of type file and we will call this file type input field Avatar okay and then we will also have a submit button so as to submit this form okay so this is our form and as you can see we have got our form over here let me bump it up a little bit when I submit this thing it will reload the page I do not want this Behavior I want this application to behave like a single page application which means I do not want to reload the page when I submit the form for this I can do this I can attach an Handler called on submit and on this event I will call this method on submit so I will create this on submit method and I will take one argument I mean this thing gets one argument and that is the event that react dispatches so I will use this event to prevent the default Behavior so now the form will not reload when I press the submit button and this is the behavior I want now let's also submit this data to a server so let's suppose a server is hosted on localhost 8000 port for the time being although it does not exist as of now but let's assume that it does okay so in order to submit this data we can do something like this try and we will do constant response a weight Fetch and then the URL of the server for this thing we are going to use the proxy utility from create react application because otherwise if the request is going to go to some other servers the browser is going to throw the course error which we do not want to address that error we have to use the proxy functionality from create react application which means that I can go inside package.json over here I can introduce a new property called proxy and in this proxy I am going to mention the address of our web server the backend application is going to run on this address so if I write something like this Fetch and then profile this thing will go to http localhost 8000 slash profile instead of going to where this react server is running so I will submit it as a post a request and I will attach the form data to it now how can I obtain form data we have to create form data how we can create form data let's see so here you will do constant form data new form data okay and then we will attach the file selected to it so form data will take a key value pair so R key is going to be Avatar and then we are going to attach our file as the value how can we attach this file to this value for that we have to create a reference so we will create file input and it will be a reference create ref from react so we will first import it from react create ref and from react okay and this is going to be our very first line and we will remove this logo okay so using this thing we can actually get the Dome element using ref so we are in fact breaking out of reacts boundary and taking the direct control of this input Dom element using this rev so what we are going to do we are going to assign this file input this file input ref to this field we will do something like ref and then file input okay so as soon as your application boots up and everything is ready to go react will bind the underlying Dome element of this input field to this ref and that way we can access the value that is inside this input field now we can come back to this Avatar key and now we can attach our value file input dot current because this is where react is going to populate the current value of this domain element and then we can access value okay and then we can simply attach this form data to our request and now let's complete this try catch block first so if there is any error while sending the request we can log it for the time being so error.message in a real word scenario you will probably log it somewhere safe so that you can come back to it later and address what has gone wrong with your application okay but for the time being we are not going to do anything with this data except login on the console all right so now here we are going to get the response and then we can parse it so past response we can call it pass response and then await response dot Json so we are going to extract Json out of it and if the response is ok then we can have an alert that file uploaded okay and as again we are going to log an error that something has gone wrong so let's see if our application is working so first of all we have to make it an async method because we are using a weight inside this method and let's see what is happening so get this thing cleared and choose a file I can choose the thumbnail I created yesterday and submit it and nothing happened so let's see what happened we can open the debugger console of our browser and over here you can see that it is telling us that form data is not a function okay so let's see what is happening okay so I bought typos form data dot set this is how you set a key value pair inside form data so hopefully things should work now clear this thing and submit it again now it says that profile route is not found of course it is not found because we do not have a backend server yet so let's go back and create a backend server so launch your terminal open a new terminal window and here create a new directory called backend CD to this directory and do npm init Y and quickly install Express as well because that is required okay now open this folder create a new file called index.js and in this thing we are going to create our Express server so quickly do that in Express and then require Express constant app Express and app Dot listen and we are going to listen on any port so for the time being let's create a variable called port and this thing will either take its value from port or get initialized to a default value of 8000 okay if we specify a port environment variable it will take its value from there otherwise it will start the application on 8000 port and since it is going to be a string we have to convert it to a number here we can do port and we can also have a callback function which simply tells us that server is running at the end report okay so let's quickly test this thing so we can do node index.js okay so our server has been started we can go back to the browser open a new tab and type in localhost 8000 okay for some reason it is attaching https but we do not want https and now we are getting cannot get slash so this is a signature message from Express this ensures that our server is running now we need to attach a route called profile for this thing we are going to create a new route in a separate file so you can say that we are going to create a new module so let us quickly create a new file let's call it profile.js and this new file or a module is responsible for offering all the functionalities related to user's profile like updating the user profile deleting the user profile and doing anything else with user profile so all of that functionality is abstracted away in this particular module so let us quickly create it for this thing we have to create an Express router so let's quickly create a router Express and then constant router equals to Express dot router I have covered all of these things in my video series about Express so in case you haven't watched it make sure you watch that before jumping into this video and then we can have a route post and then profile so this route will get the request from the fetch request which we have created on the front end okay so quickly log whatever we are getting rack dot body as of now let's see what we get and now we have to export this thing module dot exports and then the router and let's come back to the index file in the backend and require our newly created profile router so profile and then require require the application I mean the router and now we can use this router and mounted on the profile path okay so we have completed our setup for this profile router okay now we have done one mistake that here we have mounted the profile router on this profile route and in the profile.js file we have also done this thing so the absolute route for this thing will become localhost 8000 then profile slash profile which we do not want we simply want to host it on slash profile so in this case since we have profile over here we are going to get rid of this profile so it will be simply this now it will come to this route okay so this is the intended use case now let's quickly reload our server and see if our request is lending correctly on the backend because we already have the proxy in place okay so submit this data again we are getting to see localhost 404 which means that our request is not Landing properly on a server so the primary reason is that after writing this proxy thing we haven't restarted our server so let's quickly restart this thing now most probably it will work okay so let's check whether our profile is working so we will go to profile okay it is working and let's quickly attach a new file to our restarted application and submit it now you can see that there is no console error let's go to the networks tab I will Zoom this network tab as well and let's see so it submitted the request but nothing has written learned from that route it says pending which means that our request is lending correctly on profile most probably Let's see we are getting to see this undefined which means that profile has entertained our request because react.body is undefined as of now so let's complete the request by doing rest dot status 2000 and then returning a Json message so this will complete the request and we would not see this pending state so we can message like okay we can do something like this let's restart our application okay and clear this thing resubmit it again and now you can see that file uploaded because the server has responded with a 200 response and on the component side we have coded that if the response is okay issue an alert called file uploaded but in fact the file hasn't been uploaded now we need to install Express File upload package in order to actually upload the file let's do that go back to your terminal stop your backend application install Express File upload come back to your profile router and in here import that package express file upload and use this thing on this router so use it as a middleware file upload okay let's restart this application but let's do one thing go to the package Json of backend and inside this script create a new script called start and in this write node dot index.js you can do one more thing you can go one step further and install load bone so as to automatically reload the server Whenever there are changes into your files so let's quickly install install hyphen saved F because it is going to be a development time dependency and install load mod okay now instead of doing node you can do node mon index.js so this will automatically restart your backend application Whenever there are file changes into this backend folder so let's quickly test this thing npm Run start okay so Node 1 is started monitoring our files and the server had been started for us we can again try submitting our file it says file uploaded which means that the request has landed correctly on profile but again nothing has been uploaded as we have seen that Express File upload package actually populate rack dot files so let's see what is inside rack.files so as you can see that server has been restarted okay so if I submit this thing you will get to see that in reg dot files as of now there is nothing so let's see what is happening so if we over to this network Tab and click on the request and inside this payload thing you will get to see that it has got f as this value right but we we do not want this value we need actual data so for that we have to go inside our component file we have to get the actual value which will be under current dot files and it is going to be an array so we need the first element from that array so let's see what comes after doing this change inside the FTA property so submit this thing now and click on this thing now you can see that it is a binary file which is what we want to send to the server we did not want to send the text Data containing the absolute path of that file but we wanted to send the actual file right now it is sending actual file which is represented as binary and on the server side let's see if we have got our data so this is the log from backend and we have gotten our data so the file is getting received on the server side now we have to save this file to somewhere safe so that we can refer to this file whenever we want to so on the backend folder we are going to create a new folder called assets and we are going to move all our user uploaded files to this folder so let's get back to the profile module and inside this first of all we are going to receive the file so it contains a property called Avatar because that's what we are calling it on the front end side so we can destructure this property from reg dot files and now we want to move it to the assets folder so first of all let's get the proper part to the asset folder for that we are going to use path from node so require path and now we are going to create the absolute part to the assets folder so it is going to be constant assets folder and then path dot join their name so this is a utility variable which denotes the present working directory from where the program is running okay so you get the present working directory of the script and then we have to go inside the asset directory so this is going to be the absolute part to the assets folder now we can do something like Avatar dot MV so this MV thing is the utility method from Express File upload you can search for Express File upload go to npm and form here you can go to the actual repository of this package and if you scroll down here you will get to see all the utility methods that are there so we have got rack dot files dot file name dot MV so we have destructured the file from rack dot files so we can simply access that file object.mv so this is our file object Avatar and then we can do MV and in here we are actually going to move our binary file to this asset folder so this MV method takes a string which denotes the absolute path and the file name so it is going to be path dot boin the assets folder so this is the folder and then the actual file name of the file that is uploaded so it will be under Iowa DOT name okay so let's do this save this thing and come back to our application close everything now clear this network stack as well and press submit it says file uploaded let's see if assets had caught anything if I expand this you can see my tech stack 2023.png has been uploaded so this way you can upload the files to the server now let's also do some error handling so if we encounter any error while uploading the file we will return an error instead of 200 so it will be inside a try catch block and if there is any error we are going to return a 500 along with the actual error so it can be something like message and then e Dot message so here if the movement is successful a 200 response will be written if it is not successful it throws an error then a 500 error will be returned then you can handle it accordingly as we have already written the code over here so this way you can create an upload functionality for your react and express application in case you have any doubt in case you want to see more of such stuff make sure you leave a comment with your request in the comment section and in case you love this video make sure you give this video a thumbs up because that will really motivate me to produce more such awesome stuff for you guys and in case you have any other question related to programming and solopreneurship or anything else to software development make sure you follow me on Twitter and ask your questions there also I have a Discord Group which you can join the links are in the video description and I see you guys over in the next video
Info
Channel: CodeLit
Views: 5,276
Rating: undefined out of 5
Keywords: full stack development, web development, file upload, node file upload, express file upload, react file upload, upload image web, how to upload image on website
Id: 73SpYrjsNlk
Channel Id: undefined
Length: 24min 40sec (1480 seconds)
Published: Wed Feb 01 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.