How to Upload a File in React and Nodejs?

By Prajwal Haniya

Tech-letter #10 | February 18, 2023

File uploading is one of the essential features required for mobile and web applications. I have searched quite a lot on the internet to send a file from the front-end interface to the node server in the back-end. I found very few resources that explained well so that anybody could understand the process in a simple manner.

Before moving ahead let’s make a simple UI in react for providing the upload feature

// all your react boilerplate code goes above like import etc
function UploadFile() {
		const [file, setFile] = useState();

		const fileUploadHandler = (e) => {
				setFile(e.target.files[0]);
		};

		const uploadFile = () => {
			// make your API call here 
		};

		return (
				<div>
						<input type="file" name="upload file" accept=".csv" onChange={fileUploadHandler} />
						<button onClick={uploadFile}>Upload</button>
				</div>
		);
}

FormData is one such concept that we must know before we proceed.

What is FormData?

FormData is a built-in JavaScript object that allows you to easily construct a set of key-value pairs that represent form fields and their values. You can create a FormData object through const formData = new FormData();. When you create a new FormData object, you can add fields to it using the append() method.

so the code will be like

const formData = new FormData();
formData.append('file', file, file.name);

// make API calls and pass the formData along with it

The above code can be confusing. But, stick with me you will understand it better when we move ahead.

Now let’s make an API call using the axios library and send the data to the node server. You can also use XMLHttpRequest but I recommend using the axios as it can speed up your simple implementation.

To send FormData using the axios package, you can use the axios.post() method with the FormData object as the data parameter.

axios({
  method: "post",
  url: "YOUR API URL",
  data: formData,
  headers: { "Content-Type": "multipart/form-data" },
});

This should work and you must receive the files on the server. But, make sure you write the back-end code properly, else can be confusing while calling the properties of an object. Sometimes you can miss out just on the file and files.

Below you can see the backend code. To make it simple the flow is nothing but

start a node server → write a simple API to read the incoming file.

const express = require('express);
const bodyParser = require('body-parser);
const PORT = 3000;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
/* 
	you can use multer to upload the file 
	to a specified folder or to the cloud
*/

app.post('/uploadFile', async (req, res) => {
		console.log(req.file) // will give the details of the file
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${PORT}`);
});

note: You may still get a lot of errors, depending on your machine. You can browse your errors online, and I am sure that you will get a fix for them.