DEV Community

smakosh
smakosh

Posted on

How to upload files to Imagekit using Next.js server actions

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=
Enter fullscreen mode Exit fullscreen mode

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>
  )
}

Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
leosouza99 profile image
Leonardo

Hi, at first, thank you for your contribution. Do you know if it's possible to upload multiple files?

Collapse
 
smakosh profile image
smakosh

Yes it's possible, I'll add that in when I have some free time

Collapse
 
leosouza99 profile image
Leonardo

Thanks, i'll be waiting!