How to File Upload in Node JS using Express?

15-Dec-2022

.

Admin

How to File Upload in Node JS using Express?

Hello Friends,

In this tutorial, you will learn how to file upload in node js using express. this example will help you reactjs nodejs upload image — how to upload an image using reactjs. We will look at an example of uploading an image path to MySQL along with the user name who uploads the image. In this article, we will implement an uploaded image in MySQL using node js and react js. Here, Creating a basic example of how to upload images in react js with code examples.

Through this tutorial; you can use react js app as the frontend and the node express js app as the backend; So, the node js express app will use node multi library to store images in the directory of the node express js app and upload an image into MySQL database.

Before starting this react js + node express js + MySQL image file upload tutorial; you’ll need to have Node.js installed which can be done by following the instructions in this tutorial.

Step 1: Create React App


Open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2: Install Axios and Bootstrap 4

Then execute the following command to install Axios and bootstrap 4 libraries into your react app:

npm install bootstrap --save

npm install axios --save

Add bootstrap.min.css file in src/App.js file:

import React from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

function App() {

return (

<div>

<h2>Upload Image in mySQL using Node js and React js</h2>

</div>

);

}

export default App;

Step 3: Create File Upload Form Component

In this step, visit the src directory of your react js app and create a form component named FileUpload.js. And add the following code into it:

import React from 'react'

import axios from 'axios';

class FileUpload extends React.Component{

const [file, setFile] = useState();

const [fileName, setFileName] = useState("");

const saveFile = (e) => {

setFile(e.target.files[0]);

setFileName(e.target.files[0].name);

};

const uploadFile = async (e) => {

const formData = new FormData();

formData.append("file", file);

formData.append("fileName", fileName);

try {

const res = await axios.post(

"http://localhost:3000/upload",

formData

);

console.log(res);

} catch (ex) {

console.log(ex);

}

};

render(){

return (

<div className="App">

<input type="file" onChange={saveFile} />

<button onClick={uploadFile}>Upload</button>

</div>

);

}

}

export default FileUpload;

Step 4: Import Component in App.js

In this step, you need to add FileUpload.js file in src/App.js file:

import React from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

import FileUpload from './FileUpload'

function App() {

return (

<div className="App">

<FileUpload/>

</div>

);

}

export default App;

Create Node Express JS Backend

Step 1: Create Node JS App

Open your terminal and execute the following command to create node js app:

mkdir my-app

cd my-app

npm init -y

Step 2: Install Express body parser and cors Dependencies

Execute the following commands to install imperative npm packages which will help us to create REST APIs for your react file upload app:

npm install express cors body-parser express-fileupload

npm install nodemon --save-dev

Step 3: Create Server.js File

In this step, create a server.js file and add the following code to it:

const express = require("express");

const fileupload = require("express-fileupload");

const cors = require("cors");

const bodyParser = require('body-parser');

const app = express();

app.use(cors());

app.use(fileupload());

app.use(express.static("files"));

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

app.post("/upload", (req, res) => {

const newpath = __dirname + "/files/";

const file = req.files.file;

const filename = file.name;

file.mv(`${newpath}${filename}`, (err) => {

if (err) {

res.status(500).send({ message: "File upload failed", code: 200 });

}

res.status(200).send({ message: "File Uploaded", code: 200 });

});

});

app.listen(3000, () => {

console.log("Server running successfully on 3000");

});

Step 4: Start Node JS App

Start the server with the following command and then you can test the form:

npm start

OR

nodemon server.js

I hope it can help you...

#Node.js Express

#Node JS