How to Upload a File with Reactjs and Nodejs

Published on Jun 23, 2018

9 min read

NODEJS

cover

Originally this article was published on Zeolearn.com

Uploading Files might seem a task that needs to be conquered especially if you are getting into web development. In this tutorial, simple AJAX based file uploads using Reactjs on front-end and Node.js back-end. This is easy to accomplish with the following technologies since the whole source code will be in one language, JavaScript. In this example, to demonstrate for connecting a Reactjs application with Node.js backend, we will be making the use of a simple file upload example. The topics we will be covering are going to be:

  • Setting up a Back-end of our app using express-generator
  • Using create-react-app to scaffold a front-end Reactjs app
  • Using axios for cross-origin API calls
  • Handling POST requests on our server
  • Using express-fileupload, a promise based library
  • Lastly, making a connection between Reactjs and Node.js

Getting Started

🔗

We will be starting without back-end first. We will write a server application with necessary configurations required to accept cross-origin requests and uploading files. First, we need to install express-generator which is the official and quickest way to start with an Express back-end application.

npm install -g express-generator

We will install this module globally from our terminal. After installing this global npm module, we have an instance of it named express to generate our project structure.

mkdir fileupload-example
express server
cd server

When changing the current directory to the project express command just scaffolded, we can observe the following structure and files:

To run this backend server on default configuration, we have to install the dependencies mentioned in package.json first.

1npm install
2npm start

Express-generator comes with following dependencies. Some of them are essential to use such as morgan and body-parser and some we can leave out for this project.

1"dependencies": {
2 "body-parser": "~1.18.2",
3 "cookie-parser": "~1.4.3",
4 "debug": "~2.6.9",
5 "express": "~4.15.5",
6 "jade": "~1.11.0",
7 "morgan": "~1.9.0",
8 "serve-favicon": "~2.4.5"
9 }

I will be adding two more packages for our configurable back-end application to behave in the way we want to.

npm install --save cors express-fileupload

cors provide a middleware function for Express applications to enable various Cross-Origin Resource Sharing options. CORS is a mechanism that allows restricted resources (in our case, API or AJAX requests) on a web page from another domain. It helps a browser and a server to communicate and can be hosted on separate domains. You will understand it more when you will see it in action.

The other module, express-fileupload is a bare minimum express middleware function for uploading files. The advantages it has it that it has support for Promises and can handle multiple file uploads.

With these two important packages added as dependencies in our project, we can now start by modifying the default Express back-end in app.js file.

1const express = require('express');
2const path = require('path');
3const favicon = require('serve-favicon');
4const logger = require('morgan');
5const cookieParser = require('cookie-parser');
6const bodyParser = require('body-parser');
7const cors = require('cors'); // addition we make
8const fileUpload = require('express-fileupload'); //addition we make
9
10const index = require('./routes/index');
11const users = require('./routes/users');
12
13const app = express();
14
15// view engine setup
16app.set('views', path.join(__dirname, 'views'));
17app.set('view engine', 'jade');
18
19// uncomment after placing your favicon in /public
20//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
21app.use(logger('dev'));
22app.use(bodyParser.json());
23app.use(bodyParser.urlencoded({ extended: true }));
24app.use(cookieParser());
25
26// Use CORS and File Upload modules here
27app.use(cors());
28app.use(fileUpload());
29
30app.use('/public', express.static(__dirname + '/public'));
31
32app.use('/', index);
33
34// catch 404 and forward to error handler
35app.use(function (req, res, next) {
36 const err = new Error('Not Found');
37 err.status = 404;
38 next(err);
39});
40
41// error handler
42app.use(function (err, req, res, next) {
43 // set locals, only providing error in development
44 res.locals.message = err.message;
45 res.locals.error = req.app.get('env') === 'development' ? err : {};
46
47 // render the error page
48 res.status(err.status || 500);
49 res.render('error');
50});
51
52module.exports = app;

In the above code, you would notice that we made some additions. The first addition we did is to import packages cors and express-fileupload in app.js after other dependencies are loaded.

1const cors = require('cors'); // addition we make
2const fileUpload = require('express-fileupload'); //addition we make

Then just after other middleware functions, we will instantiate these two newly imported packages.

1// Use CORS and File Upload modules here
2app.use(cors());
3app.use(fileUpload());

Also, we need to allow data coming from a form. For this, we have to enable urlencoded options of body-parser module and specify a path as to store the image file coming from the client.

1app.use(bodyParser.urlencoded({ extended: true }));
2
3// below, also change this to
4app.use('/public', express.static(__dirname + '/public'));

With this, we can see if our server is working correctly by running:

npm start

If you get the screen below by navigation on port http://localhost:3000, it means that our server is running.

Before we move to generate our front-end application, we need to change to port for our backend since front-end application generated using create-react-app will also be running on port 3000. Open bin/www file and edit:

1/**
2 * Get port from environment and store in Express.
3 */
4
5// 3000 by default, we change it to 4000
6
7var port = normalizePort(process.env.PORT || '4000');
8app.set('port', port);

Setting up Front-end

🔗

create-react-app is another command line utility that to generate a default Reactjs front-end application.

create-react-app node-react-fileupload-front-end

We will also install the required library we are going to use for making API calls to our backend server.

yarn add axios

index.js is the starting point of our application in the src/ directory. It registers the render function using ReactDOM.render() by mounting App component. Components are the building blocks in any Reactjs application. This App component comes from src/App.js. We will be editing this file in our front-end source code.

File Upload Form

🔗

We will be using the HTML form element that has an input which provides access to the value, that is the file, using refs. Ref is a special attribute that can be attached to any component in React. It takes a callback function and this callback will be executed immediately after the component is mounted. It can be also be used on an HTML element and the callback function associated will receive the DOM element as the argument. This way, ref can be used to store a reference for that DOM element. That is exactly what we are going to do.

1class App extends Component {
2 // We will add this part later
3
4 render() {
5 return (
6 <div className="App">
7 <h1>FileUpload</h1>
8 <form onSubmit={this.handleUploadImage}>
9 <div>
10 <input
11 ref={ref => {
12 this.uploadInput = ref;
13 }}
14 type="file"
15 />
16 </div>
17 <br />
18 <div>
19 <input
20 ref={ref => {
21 this.fileName = ref;
22 }}
23 type="text"
24 placeholder="Enter the desired name of file"
25 />
26 </div>
27 <br />
28 <div>
29 <button>Upload</button>
30 </div>
31 <hr />
32 <p>Uploaded Image:</p>
33 <img src={this.state.imageURL} alt="img" />
34 </form>
35 </div>
36 );
37 }
38}

The input element must have the type="file" otherwise it would not be able to recognize what type we are using it for. It is similar to the values like email, password, etc.

The handleUploadImage method will take care of the API calls that we need to request to the server. If that call is successful, the local state of our React application will be set to let the user know that the upload was successful. Inside this function, to make the API call, we will be using axios library we installed when setting up our front end app.

1constructor(props) {
2 super(props);
3
4 this.state = {
5 imageURL: ''
6 };
7
8 this.handleUploadImage = this.handleUploadImage.bind(this);
9 }
10
11 handleUploadImage(ev) {
12 ev.preventDefault();
13
14 const data = new FormData();
15 data.append('file', this.uploadInput.files[0]);
16 data.append('filename', this.fileName.value);
17
18 fetch('http://localhost:4000/upload', {
19 method: 'POST',
20 body: data
21 }).then(response => {
22 response.json().then(body => {
23 this.setState({ imageURL: `http://localhost:4000/${body.file}` });
24 });
25 });
26 }

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data but can be used independently from forms in order to transmit keyed data. To build a FormData object, instantiating it then appending fields to it by calling its append() method like we did above.

Since we are not using any styling, our form looks bare minimum and ugly. But you can go ahead and make it look more professional. For brevity, I am going to keep things simple. I recommend you to always enter a file uname, other wise it will store the file on the with undefined.jpg name.

Updating the server to handle AJAX Request

🔗

Right now, we do not have in our server code to handle the POST request React app makes a request to. We will add the route in our app.js in our Express application where the default route is defined.

1app.post('/upload', (req, res, next) => {
2 // console.log(req);
3 let imageFile = req.files.file;
4
5 imageFile.mv(`${__dirname}/public/${req.body.filename}.jpg`, err => {
6 if (err) {
7 return res.status(500).send(err);
8 }
9
10 res.json({ file: `public/${req.body.filename}.jpg` });
11 console.log(res.json);
12 });
13});
npm start

This route gets triggered when a request is made to /upload/. The callback associated using the route contain req, res objects and access to next, a standard way of defining a middleware function in an Express application. The req object has the file and the filename that was uploaded during form submission from the client application. If any error occurs, we return the 500 server error code. Otherwise we return the path to the actual file and console the response object to check if everything is work as we expect it.

.mv file is promise-based and provided to us by the express-fileupload package we installed earlier. Try uploading an image file from the client now. Make sure both the client and server are running from different terminal tabs at this point. If you get a success message like this in your terminal:

POST /upload 200 98.487 ms - 25
GET /public/abc.jpg 200 6.231 ms - 60775

At the same time, the client is requesting to view the file on the front-end with a GET HTTP method. That means the route /upload from the browser is successfully called and everything is working fine. Once the file is uploaded on the server and it will be sent back to the client to reflect that the user has successfully uploaded the file.

You can find the complete code for this example at FileUpload-Example Github Repository.


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.