I can’t send file from my NextJS front end to my Codeigniter 4 backend. My Codeigniter can’t read the file sent from NextJS.
I’m using server action for my form like this.
Form Component
export default function UploadInvoiceButton({
submission,
}: {
submission: Submission;
}) {
const [state, formAction] = useFormState(uploadInvoice, undefined);
return (
<form action={formAction}>
<input type="hidden" name="id" value={submission.id} />
<div className="flex flex-col gap-2 mb-4">
<Label htmlFor="invoice" className="text-sm">
Invoice File
</Label>
<Input
type="file"
id="invoice"
name="invoice"
aria-describedby="invoice-errir"
/>
<div id="invoice-error">
{state?.error &&
state.message?.map((error: string) => (
<p key={error} className="text-red-500 text-sm">{error}</p>
))}
</div>
</div>
<div className="w-full justify-end">
<div className="flex w-1/2 gap-2">
<Button type="button" variant={"secondary"}>
Batal
</Button>
<SubmitButton>Upload</SubmitButton>
</div>
</div>
</form>
)
And here is my Server Action
const uploadInvoiceSchema = z.object({
invoice: z
.any()
.refine((value) => {
return value instanceof File;
})
.refine((value) => value.size > 0, {
message: "File invoice harus dipilih",
})
.refine(
(invoice) => {
return invoice.type === "application/pdf";
},
{
message: "File invoice harus berformat PDF",
}
)
.refine((invoice) => invoice.size < 2000000, {
message: "Ukuran file invoice maksimal 2MB",
}),
});
export async function uploadInvoice(
prevState:
| {
error?: boolean;
message?: string[];
}
| undefined,
formData: FormData
) {
const validatedFields = uploadInvoiceSchema.safeParse({
invoice: formData.get("invoice"),
});
if (!validatedFields.success) {
return {
error: true,
message: validatedFields.error.flatten().fieldErrors.invoice,
};
}
const { invoice } = validatedFields.data;
if (!(invoice instanceof File)) {
return {
error: true,
message: ["File invoice harus dipilih"],
};
}
const token = cookies().get("accessToken")?.value;
const body = new FormData();
body.append("invoice", invoice);
console.log("body", body);
const response = await fetch(
`${process.env.API_URL}/submissions/${formData.get("id")}/upload-invoice`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
body: body,
}
);
const responseJson = await response.json();
if (!response.ok) {
return {
error: true,
message: ["Gagal upload invoice"],
};
}
revalidatePath(`/dashboard/submission/monitor/${formData.get("id")}`, "page");
return {
error: false,
message: ["Berhasil upload invoice"],
};
}
The result of the console.log(body)
is like this
FormData {
invoice: File {
size: 1757482,
type: 'application/pdf',
name: 'Laporan Aktualisasi _Herlina 23 feb Citeko copy.pdf',
lastModified: 1720162046799
}
}
There should be a file in it right?
But on my Codeigniter 4, when i try to use log_message
to check the value of $this->request->getFile('invoice')
, it’s just return {}