File upload with Node & React
SUPPORT ME BY READING THE ARTICLE FROM IT’S ORIGINAL SOURCE
To new developers, file upload feels like a complex topic. However, for a non-complex app (meaning you won’t handle heavy image/video/file optimisation) file upload is nothing more than copying files from one place to another. The Express framework for Node makes this simple.
All the files can be seen here at https://github.com/AntonioErdeljac/file-upload-tutorial. The following is a demo the application that we will be building:
Bootstraping the app
We will start by creating the frontend using create-react-app
and backend using express-generator
.
Frontend
npx create-react-app frontend
cd frontend
npm start
Backend
npm install express-generator -g
express backend
cd backend
npm install
npm start
Setting up the frontend
In frontend/src/index.js
:
We will simply render the main <App/>
component.
In frontend/src/App.jsx
:
This is the entry component that has the title and the <Main/>
component.
In frontend/src/components/Main.jsx
:
The following component has a form with file upload input and file name input. Upon submitting, the handleUploadImage
function will be called. The function will alter state’s imageURL
of uploaded image which is used as the href property in image tag on the bottom.
Setting up the backend
Start by installing CORS & express-fileupload package and use nodemon to watch changes on the file.
cd backend
npm install --save cors
npm install --save express-fileupload
npm install -g nodemon
nodemon app.js
Modify the app.js file in backend folder to look as the following:
Finally, route to localhost:3000 and upload a file.
To see the entire project, visit https://github.com/AntonioErdeljac/file-upload-tutorial