Next.js File Upload API Tutorial (local directory)

Owais Shah
2 min readNov 20, 2023

--

Overview

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

import { NextResponse } from "next/server";
import path from "path";
import { writeFile } from "fs/promises";

export const POST = async (req, res) => {
const formData = await req.formData();

const file = formData.get("file");
if (!file) {
return NextResponse.json({ error: "No files received." }, { status: 400 });
}

const buffer = Buffer.from(await file.arrayBuffer());
const filename = file.name.replaceAll(" ", "_");
console.log(filename);
try {
await writeFile(
path.join(process.cwd(), "public/assets/" + filename),
buffer
);
return NextResponse.json({ Message: "Success", status: 201 });
} catch (error) {
console.log("Error occured ", error);
return NextResponse.json({ Message: "Failed", status: 500 });
}
};

Code Explanation

// 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 });
}
};

Usage

Uploading a File

To upload a file, make a POST request to the API endpoint (/api/upload) with the file included in the request payload as a form data field named "file". The API will handle the file processing and save it to the server in the public/assets/ directory with a modified filename.

Example using `fetch` in Next js (frontend)

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));

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
}

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

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

--

--