Form
It's common for file uploads to be part of a form. In this guide, we'll take a look at how to add file uploads to a form built using shadcn/ui. This guide will assume you have a basic understanding of:
This guide is for uploading multiple files, but the same principles apply for single file uploads.
Form with upload dropzone
Installation
To follow along with this guide, install the following shadcn/ui components:
This will also automatically install all required dependencies.
Set up upload route
Set up your upload route. Use your preferred framework, but for this example, we'll use Next.js.
We create the upload route form
for multiple files. All files will have the same prefix form/
in the S3 bucket.
Define the form schema
We'll now create the form. The form uses the Upload Dropzone component to allow users to upload files. The form also has an input field for arbitrary text.
Define the form schema using zod
. The schema contains two fields:
folderName
: For the arbitrary text input.objectKeys
: For the uploaded files, stores the S3 object keys.
Define the form
Use the useForm
hook from react-hook-form
to create the form.
Also use the useUploadFiles
hook to handle the file uploads.
Feel free to make changes to the code to suit your needs, such as calling your API on onSubmit
.
Optional: Hide dropzone after upload
Now let's hide the dropzone after the user has uploaded files. We can do this by using the uploadedFiles
array returned by the useUploadFiles
hook.
Advanced: Upload on form submit
In this example, we only upload the files after the user clicks on the submit button. We use the uploadOverride
prop to override the default behavior of the <UploadDropzone />
.
The full code example for the form is below.