iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📂

Common Pitfalls When Implementing form-data File Uploads in Next.js for Beginners

に公開

I'm miki, primarily a backend engineer who also works as a frontend engineer on the side, but I'm a perpetual beginner when it comes to CSS.

I'm writing this as a note because I ran into a bit of a snag while implementing file uploads on the API side for work.

While the title mentions implementation with form-data, I initially considered two patterns for sending files:

  • Sending via form-data
  • Converting to base64 and sending

Base64 is easy to handle since it's just a string, but it felt like the decoding and encoding would be a hassle and costly. Since it also tends to increase the file size, I decided to go with form-data for now.
I feel like form-data is the more standard approach, but since I do see base64 conversion used in some implementations, it's probably best to compare them based on the data you're handling and your storage method.

Sample implementation of form-data transmission

Frontend

import axios from "axios";

export default function Images() {
  const handleUploadClick = async (e) => {
    const file = e.target.files[0];
    const formData = new FormData();
    formData.append('file', file);

    try {
      await axios.post(`アップロード先エンドポイント`,
        formData
      );
    } catch (e) {
      console.error(e);
    }
  };

  return (
    <div style={{ padding: 20 }}>
      <label htmlFor="upload-button" style={{ border: "1px solid #222", borderRadius: 10, padding: 10, cursor: "pointer" }}>
        <input
          accept="image/*"
          id="upload-button"
          type="file"
          onChange={handleUploadClick}
          hidden
        />
        Choose file
      </label>
    </div> 
  );
};

Backend

const formidable = require("formidable");

// I didn't realize this was necessary ↓
export const config = {
  api: {
    bodyParser: false,
  },
};

export default async (req, res) => {
  if (req.method !== "POST") return;

  const form = new formidable.IncomingForm();

  form.parse(req, async function (err, fields, files) {
    if (err) {
      res.statusCode = 500;
      res.json({
        method: req.method,
        error: err
      });
      res.end();
      return;
    }
    const file = files.file;
    // Do something with the file
  });
};

The Pitfall I Didn't Notice for a While

I was initially implementing this without the config part below:

// I didn't realize this was necessary ↓
export const config = {
  api: {
    bodyParser: false,
  },
};

I spent some time wondering why the file wasn't being parsed. It seems that Next.js parses request.body by default... As a result, the file couldn't be received as a stream.

So, I checked the Next.js API Middleware documentation...
https://nextjs.org/docs/api-routes/api-middlewares#custom-config

bodyParser is automatically enabled. If you want to consume the body as a Stream or with raw-body, you can set this to false.

I see.

With this, I'm now able to receive files as a stream! Happy! 🥳

Discussion