Skip to content

Instantly share code, notes, and snippets.

@adeleke5140
Created October 30, 2023 13:18
Show Gist options
  • Save adeleke5140/527f0568fe6460873f624b7a30b8909c to your computer and use it in GitHub Desktop.
Save adeleke5140/527f0568fe6460873f624b7a30b8909c to your computer and use it in GitHub Desktop.
An API route to convert a base64 encoded image ans save it to a jpeg file.
import { writeFileSync } from "fs";
import { join } from "path";
import { NextApiRequest, NextApiResponse } from "next";
export default async (req: NextApiRequest, res: NextApiResponse) => {
try {
if (req.method === "POST") {
const base64 = req.body.image;
const cleanBase64Data = base64.replace(/^data:image\/jpeg;base64,/, ""); // Remove the data URI prefix
const binaryData = Buffer.from(cleanBase64Data, "base64");
const filePath = join(process.cwd(), "public", "images", "profile.jpeg");
writeFileSync(filePath, binaryData);
res.status(200).json({ message: "Image saved successfully" });
} else {
res.status(500).json({ message: "Method no allowed" });
}
} catch (err) {
console.error(err);
res.status(500).json({ message: "Internal server error" });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment