,

Uploading files and images with Multer in React, Node.js, and Express.js | MERN Stack | Full Stack Tutorial #4

Posted by


In this tutorial, we will learn how to upload files, such as images, using Multer in a React + Node.js + Express.js application. Multer is a popular middleware for handling file uploads in Node.js applications. We will be using the MERN stack, which consists of MongoDB, Express.js, React, and Node.js.

This tutorial assumes that you have some prior knowledge of the MERN stack and have a basic understanding of how to set up a MERN stack application. If you are new to the MERN stack, I recommend checking out some introductory tutorials before proceeding with this one.

Let’s get started by setting up our backend with Node.js and Express.js:

Step 1: Set up a Node.js project
First, create a new directory for your project and navigate into it. Run the following command to initialize a new Node.js project:

npm init -y

This command will create a package.json file in your project directory.

Step 2: Install dependencies
Next, install Express.js and Multer by running the following command:

npm install express multer

Step 3: Create an Express.js server
Create a new file called server.js in your project directory. This file will serve as the entry point for our backend server. Add the following code to set up a basic Express.js server:

const express = require('express');
const multer = require('multer');
const app = express();
const port = 5000;

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Step 4: Configure Multer for file uploads
Next, configure Multer to handle file uploads. Add the following code to your server.js file:

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, file.originalname);
  }
});

const upload = multer({ storage: storage });

In this code snippet, we create a disk storage engine for Multer that specifies the destination directory for uploaded files. We then create an instance of Multer with this storage engine.

Step 5: Handle file uploads
Now that we have configured Multer, let’s add a route to our Express.js server for handling file uploads. Add the following code to your server.js file:

app.post('/upload', upload.single('file'), (req, res) => {
  res.json({ file: req.file });
});

In this code snippet, we define a POST route at /upload that uses the upload.single() middleware to handle a single file upload. The uploaded file can be accessed through the req.file object, which contains information about the uploaded file.

Step 6: Set up a file upload form in React
Next, let’s set up a file upload form in our React frontend to test our file upload functionality. Create a new React project by running the following command:

npx create-react-app frontend

Once your React project is created, navigate into the frontend directory and open the App.js file. Add the following code to create a basic file upload form:

import React, { useState } from 'react';

function App() {
  const [file, setFile] = useState(null);

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

  const handleSubmit = async (e) => {
    e.preventDefault();

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

    const response = await fetch('http://localhost:5000/upload', {
      method: 'POST',
      body: formData
    });

    const data = await response.json();
    console.log(data);
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="file" onChange={handleFileChange} />
        <button type="submit">Upload File</button>
      </form>
    </div>
  );
}

export default App;

In this code snippet, we create a file upload form with an input field for selecting a file, and a submit button for uploading the file to the server using a POST request.

Step 7: Test the file upload functionality
To test the file upload functionality, start your backend server by running the following command in your project directory:

node server.js

Next, start your React frontend by navigating into the frontend directory and running the following command:

npm start

Open your browser and navigate to http://localhost:3000 to view your React frontend. Select a file using the file input field and click the "Upload File" button to submit the file to the server. The server should respond with a JSON object containing information about the uploaded file.

Congratulations! You have successfully set up a file upload functionality using Multer in a React + Node.js + Express.js application. Feel free to customize the code to suit your specific requirements and explore more features of Multer for handling file uploads in your projects.

0 0 votes
Article Rating
7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jzzker
1 month ago

พี่ครับผมได้ได้ Extension ที่เอาเม้าชี้แล้ว มันขึ้นรายระเอียดว่า เมทตอนนี้ทำอะไรยังไง ต้องอิ่มพอตไรมางี้ครับ

@Rungsuriyabuethong
1 month ago

16:21 log ข้อมูล form ทำไมได้ชุดข้อมูลทั้งหมดมาครับ ที่งที่ set แค่ข้อมูล file เข้าไปครับ

@kingphetxaykinkeo4876
1 month ago

รูปไม่แสดงในหน้าfont endครับ ตอนเพิ่มข้อมูลและรูปภาพมันก็เข้าอยู่ใน Server อยู่ครับ Console log Data ออกมาก็มีข้อมูล ข้อมูลรูปภาพมันเป็นชื่อรูปภาพที่เราsetค่าไว้และก็นามสกุลไฟล์

@coffeeinruk
1 month ago

ขออัพโหลดแบบ multi ด้วยครับ

@ณัฐยศล่ําสัน-ช3ผ
1 month ago

พี่ครับ e.target.files fileเติมs มาอยางไงหรอครับ🙏🙏

@midserchannel1258
1 month ago

ถ้าไม่มี folder uploads อยากให้ server สร้างเอง ต้องเขียนแบบไหนครับ
Image นะครับ

@delphidelphidelphi
1 month ago

อยากให้ทำถึงตอน เอาไปใช้จริงด้วยนะครับ ว่าต้องทำยัไงบ้าง ขอบคุณความรู้ดีๆครับ…