DEV Community

Cover image for Upload Photos with React and Express using Multer: A Comprehensive Guide
Jose Latines
Jose Latines

Posted on

Upload Photos with React and Express using Multer: A Comprehensive Guide

1. 🚀 Install the necessary dependencies on your server

To get started, install the multer package by running the following command:

npm install multer
Enter fullscreen mode Exit fullscreen mode

2. 🌐 Add endpoints for image upload and access

We will create two endpoints: POST /api/images for uploading images from our frontend and GET /images/{imageName} to access the uploaded images.

Here's an example code snippet for these endpoints:

// index.js
import { createReadStream } from "fs";
import multer from "multer";
const upload = multer({ dest: "images/" });

// app.use('/images', express.static('images'))
app.get("/images/:imageName", (req, res) => {
    // do a bunch of if statements to make sure the user is
    // authorized to view this image, then

    const imageName = req.params.imageName;
    const readStream = createReadStream(`images/${imageName}`);
    readStream.pipe(res);
});

app.post("/api/images", upload.single("image"), (req, res) => {
    const imageName = req.file.filename;
    const description = req.body.description;

    // Save this data to a database probably

    console.log(description, imageName);
    return res.send({ description, imageName });
});

Enter fullscreen mode Exit fullscreen mode

React code

1. ✨ Create an image uploader component in React

In the component, we will define a submit function that makes the API request in the parent component. This makes the component reusable.
The submit function should accept the event (e), the file, and a description of the image.

// components/FileUploader.jsx
import { useState } from "react";

function FileUploader({ submit }) {
    const [file, setFile] = useState();
    const [description, setDescription] = useState("");

    return (
        <div className="row">
            <form onSubmit={e => submit(e, file, description)}>
                <input
                    filename={file}
                    onChange={e => setFile(e.target.files[0])}
                    type="file"
                    accept="image/*"
                ></input>
                <input
                    onChange={e => setDescription(e.target.value)}
                    type="text"
                ></input>
                <button type="submit">Submit</button>
            </form>
        </div>
    );
}

export default FileUploader;

Enter fullscreen mode Exit fullscreen mode

2. ✨ Implement the component

import axios from "axios";
import FileUploader from "./Components/FileUploader";

function App() {
    const sendImage = async (e, file, description) => {
        e.preventDefault();

        const formData = new FormData();
        formData.append("image", file);
        formData.append("description", description);

        const result = await axios.post(
            "http://localhost:8080/api/images",
            formData,
            {
                headers: { "Content-Type": "multipart/form-data" },
            }
        );
        console.log(result.data);
    };
    return (
        <>
            <FileUploader submit={sendImage} />
        </>
    );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Enjoy!

Now it's time to turn on your servers and start using this image uploader in your application. 🎉

Note: The multer package has multiple configurations, such as handling multiple files, setting file size limits, and more. In this tutorial, we will keep it simple and focus on the basics.

If you found this content helpful, please let me know in the comments section and don't forget to follow me on Instagram @gregglatines. 😊

Top comments (0)