Building a File Upload API with Express and Multer
Published: 2024-03-10 11:42:35

In this tutorial, we'll create a simple file upload API using Express, a popular Node.js framework, and Multer, a middleware for handling file uploads. This API will allow clients to upload image files to the server. Let's break down the steps.

## Step 1: Set Up Your Project

Start by initializing a new Node.js project and installing the required dependencies:

```bash
npm init -y
npm install express multer
```

Create an entry file, such as `index.js`, and set up your Express server:

```javascript
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const app = express();
const PORT = process.env.PORT || 3000;

// ... [Continue reading the code in the article]
```

For the complete code, please visit the [GitHub repository](https://github.com/openai/dev.to-express-multer-upload).

## Step 2: Configure Multer for File Uploads

Define the storage configuration for Multer to specify where and how to save the uploaded files. Set up the Multer middleware with options for file size limits, allowed file types, and custom file filtering.

```javascript
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = path.join(__dirname, 'uploads');
    fs.mkdirSync(uploadPath, { recursive: true });
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`);
  },
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5, // Limit file size to 5 MB
  },
  fileFilter: (req, file, cb) => {
    const allowedMimes = ['image/jpeg', 'image/png', 'image/gif'];

    if (allowedMimes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('Invalid file type. Only JPEG, PNG, and GIF are allowed.'));
    }
  },
});
```

## Step 3: Implement the File Upload Route

Continuing from where we left off, let's handle the uploaded image and respond with relevant information:

```javascript
app.post('/upload', upload.single('image'), (req, res) => {
  try {
    // Handle the uploaded image
    const imageBuffer = req.file.buffer;

    // Perform further processing or save to storage (e.g., database, file system)
    // For now, let's save it to the 'uploads' directory
    const imagePath = path.join(__dirname, 'uploads', req.file.filename);
    fs.writeFileSync(imagePath, imageBuffer);

    // Respond with success message and additional information
    res.status(200).json({
      message: 'Image uploaded successfully!',
      filename: req.file.filename,
      path: `/uploads/${req.file.filename}`,
    });
  } catch (error) {
    console.error('Error uploading image:', error.message);
    res.status(500).json({ error: 'Error uploading image' });
  }
});

// Set up static serving for the 'uploads' directory
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

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

In this continuation, we handle the uploaded image by saving it to the 'uploads' directory. The server then responds with a success message and additional information, including the filename and path.

## Step 4: Run Your Express Server

Now, it's time to run your Express server. Make sure you've created the 'uploads' directory in the same folder as your server script. Run the following command in your terminal:

```bash
node index.js
```

Your server should now be running at [http://localhost:3000](http://localhost:3000).

## Step 5: Test Your File Upload API

With your Express server up and running, you can test the file upload API. Use your preferred API testing tool or create a simple HTML form to send a POST request to the '/upload' endpoint.

### HTML Form Example:

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Upload Test</title>
</head>
<body>
  <form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="image" accept="image/*" />
    <button type="submit">Upload Image</button>
  </form>
</body>
</html>
```

Replace the form action with your server's URL.

That's it! You've successfully created a file upload API with Express and Multer. Feel free to customize the code based on your project requirements.

Happy coding!