One click image upload form

I want to create a one click image upload button, ideally using next JS's server actions. i would like to have a form, in which the only element is an input field that the user can upload a file to, as soon as the file is uploaded - I want the form to be submitted, and the server action to run. Currently - i am doing this like so.
function UploadImageButton({ ...otherProps }: React.ButtonHTMLAttributes<HTMLButtonElement>) {
const { form, action, handleSubmitWithAction, resetFormAndAction } = useHookFormAction(
uploadImageAction,
zodResolver(uploadImageSchema),
{
actionProps: {},
formProps: {},
errorMapProps: {},
}
);

return (
<form onSubmit={handleSubmitWithAction}>
<Button
{...otherProps}
className="flex flex-row items-center justify-center gap-1 relative overflow-hidden"
size={"sm"}
>
{action.isPending ? (
<StandardLoadingSpinner />
) : (
<>
Upload <ImageUp className="w-4 h-4" />
<input
className="opacity-0 absolute hover:cursor-pointer"
type="file"
onChange={(e) => {
if (e.target.files?.[0]) e.target.closest("form")?.submit();
}}
onClick={(e) => {
const element = e.target as HTMLInputElement;
element.value = "";
}}
accept="image/png, image/jpeg"
/>
</>
)}
</Button>
</form>
);
}
function UploadImageButton({ ...otherProps }: React.ButtonHTMLAttributes<HTMLButtonElement>) {
const { form, action, handleSubmitWithAction, resetFormAndAction } = useHookFormAction(
uploadImageAction,
zodResolver(uploadImageSchema),
{
actionProps: {},
formProps: {},
errorMapProps: {},
}
);

return (
<form onSubmit={handleSubmitWithAction}>
<Button
{...otherProps}
className="flex flex-row items-center justify-center gap-1 relative overflow-hidden"
size={"sm"}
>
{action.isPending ? (
<StandardLoadingSpinner />
) : (
<>
Upload <ImageUp className="w-4 h-4" />
<input
className="opacity-0 absolute hover:cursor-pointer"
type="file"
onChange={(e) => {
if (e.target.files?.[0]) e.target.closest("form")?.submit();
}}
onClick={(e) => {
const element = e.target as HTMLInputElement;
element.value = "";
}}
accept="image/png, image/jpeg"
/>
</>
)}
</Button>
</form>
);
}
This does not seem to be working as intended, as for one the page is refreshing when the file is uploaded (how do i do something similar to e.preventDefault using the form.submit() method to submit?) and the action is seemingly also not being hit/ran. Could anyone give any tips on how they've / would go about achieving this? Thanks.
No description
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server