As we're using Imagekit in this tutorial, setup an account there and grab the following keys:
IMAGEKIT_PUBLIC_KEY=
IMAGEKIT_PRIVATE_KEY=
IMAGEKIT_URL_ENDPOINT=
Add them to your .env.local
file in your Next.js project, then install the imagekit
package, finally let's create our FileUpload.tsx
component
import ImageKit from "imagekit"
const imageKit = new ImageKit({
publicKey: process.env.IMAGEKIT_PUBLIC_KEY!,
privateKey: process.env.IMAGEKIT_PRIVATE_KEY!,
urlEndpoint: process.env.IMAGEKIT_URL_ENDPOINT!,
})
const FileUpload = () => {
// Server action
const handleCreateListing = async (formData: FormData) => {
"use server"
const image = formData.get("image") as unknown as File
// You could throw an error if image is null here
const arrayBuffer = await image.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const response = await imageKit.upload({
file: buffer,
fileName: image.name,
})
// Do something with response
}
return (
<form action={handleCreateListing}>
<input name="image" type="file" />
<button type="submit">Submit</button>
</form>
)
}
That's all. You could use useFormState
to handle the pending state and show a loading state and disable the button. You could also add more validation server side in the server action etc...
Top comments (3)
Hi, at first, thank you for your contribution. Do you know if it's possible to upload multiple files?
Yes it's possible, I'll add that in when I have some free time
Thanks, i'll be waiting!