How do I upload image and text in next.js API route ? I have front end ready. here is the onSubmit function for uploading image and text. please point out what I’m doing wrong here.
Can someone help and possibly explain this to me so I can make sense of it for future reference.
Thanks
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const res = await fetch("/api/articles", {
method: "POST",
body: JSON.stringify({ formData }),
headers: { "content-type": "application/json" },
});
if (!res.ok) {
throw new Error("failed to create ticket.");
}
router.refresh();
router.push("/");
}
this is the Api endpoint
import Post from "@/app/(model)/post";
import { writeFile } from "fs/promises";
import { NextRequest, NextResponse } from "next/server";
import { join } from "path";
export async function POST(req:NextRequest, data: FormData) {
'use server'
console.log('post created')
try {
const body = await req.json()
const file: File | null = data.get("file") as unknown as File;
if (!file) {
throw new Error("No file uploaded");
}
const postData = body.formData
const bytes = await file.arrayBuffer();
const buffer = Buffer.from(bytes);
const path = join('/', 'tmp', file.name)
await Post.create(postData)
await writeFile(path, buffer)
return NextResponse.json({message: 'Post Created'}, {status: 201})
} catch (error) {
return NextResponse.json({message: 'Error', error}, {status: 500})
}
}
