DEV Community

Owais Shah
Owais Shah

Posted on

Next.js File Upload API Documentation

This documentation provides a guide on setting up and using a file upload API in a Next.js application. The provided API endpoint allows you to handle file uploads efficiently.

API Endpoint

The file upload API is defined in the POST handler, which is responsible for processing incoming file data and saving it to the server.

Image description

// Import necessary modules
import { NextResponse } from "next/server";**
import path from "path";
import { writeFile } from "fs/promises";

// Define the POST handler for the file upload
export const POST = async (req, res) => {
  // Parse the incoming form data
  const formData = await req.formData();

  // Get the file from the form data
  const file = formData.get("file");

  // Check if a file is received
  if (!file) {
    // If no file is received, return a JSON response with an error and a 400 status code
    return NextResponse.json({ error: "No files received." }, { status: 400 });
  }

  // Convert the file data to a Buffer
  const buffer = Buffer.from(await file.arrayBuffer());

  // Replace spaces in the file name with underscores
  const filename = file.name.replaceAll(" ", "_");
  console.log(filename);

  try {
    // Write the file to the specified directory (public/assets) with the modified filename
    await writeFile(
      path.join(process.cwd(), "public/assets/" + filename),
      buffer
    );

    // Return a JSON response with a success message and a 201 status code
    return NextResponse.json({ Message: "Success", status: 201 });
  } catch (error) {
    // If an error occurs during file writing, log the error and return a JSON response with a failure message and a 500 status code
    console.log("Error occurred ", error);
    return NextResponse.json({ Message: "Failed", status: 500 });
  }
};
Enter fullscreen mode Exit fullscreen mode

Usage

Uploading a File
To upload a file, make a POST request to the defined API endpoint with the file included in the request payload as a form data field named "file". The API handles the file processing and saves it to the server in the public/assets/ directory with a modified filename.

Example using fetch in JavaScript:
const fileInput = document.getElementById("fileInput"); // Replace with your HTML element ID

const file = fileInput.files[0];

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

fetch("/api/upload", {
  method: "POST",
  body: formData,
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Enter fullscreen mode Exit fullscreen mode

Response

The API returns JSON responses to indicate the success or failure of the file upload operation.

Success Response (HTTP Status Code: 201 Created)

{
  "Message": "Success",
  "status": 201
}
Enter fullscreen mode Exit fullscreen mode

Failure Response (HTTP Status Code: 500 Internal Server Error)

{
  "Message": "Failed",
  "status": 500
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)