Converting File Objects to Base64 Strings in TypeScript
Fri Apr 05 2024Introduction
With the advent of Next.js 14 and its server actions, handling File objects directly from forms has become increasingly common. This shift presents a new challenge: converting these File objects to a format that can be easily stored or transmitted. This blog post demonstrates a practical approach to converting File format objects into base64 strings using TypeScript, an essential skill for modern web development.
The Problem
Traditionally, server-side environments like Node.js handle files via paths, without direct access to File objects. However, server actions in Next.js 14 allow developers to directly receive File objects from forms, necessitating a method to convert these files into a more manageable format.
The Solution
Here's how you can convert a File object into a base64 string:
export const onSubmitHandler = async (formData: FormData) => {
try {
let image = formData.get('image')?.valueOf() as File;
const name = formData.get("product-name")?.toString();
const description = formData.get("product-description")?.toString();
const price = formData.get("price")?.toString();
const spec = formData.get("spec")?.toString();
if (image) {
const arrayBuffer = await image.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
const base64 = buffer.toString('base64');
console.log("BASE 64", base64);
const res = await sql`INSERT INTO public.products (name, description, price, specifications, imagePath) VALUES (${name}, ${description}, ${price}, ${spec}, ${base64})`;
revalidatePath("/shop");
revalidatePath("/dashboard");
console.log(res);
}
} catch (error) {
console.log(error);
}
}
This approach involves converting the File object into an ArrayBuffer, then converting that to a Buffer object, and finally encoding it as a base64 string. This base64 string can then be stored in a database or sent over the network.
Conclusion
Converting File objects to base64 strings in TypeScript is a useful technique that can help you handle file uploads more flexibly in your web applications. Whether storing images in a database or sending files to another service, this method provides a straightforward way to work with file data on the server side.