#How to upload an image with a server action in a client component?
1 messages · Page 1 of 1 (latest)
Hi @royal mirage. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To upload an image with a server action in a client component, you can use the put function from the @vercel/blob package. Here's an example of how you can do this:
First, you need to create a form in your client component where users can select the image they want to upload. This form should have an action that calls the uploadImage function when the form is submitted:
import { put } from '@vercel/blob';
import { revalidatePath } from 'next/cache';
export async function Form() {
async function uploadImage(formData: FormData) {
'use server';
const imageFile = formData.get('image') as File;
const blob = await put(imageFile.name, imageFile, {
access: 'public',
});
revalidatePath('/');
return blob;
}
return (
<form action={uploadImage}>
<label htmlFor="image">Image</label>
<input type="file" id="image" name="image" required />
<button>Upload</button>
</form>
);
}
(Source: Vercel Docs (https://vercel.com/docs/storage/vercel-blob/server-upload))
Then, you need to add the hostname to your next.config.js file including the store id from the dashboard:
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'my-blob-store.public.blob.vercel-storage.com',
port: '',
},
],
},
};
module.exports = nextConfig;
(Source: Vercel Docs (https://vercel.com/docs/storage/vercel-blob/server-upload))
This will allow you to use next/image to display images from your Vercel Blob store.
Please note that the 'use server' directive is used to mark the uploadImage function as a Server Action. This directive can be placed at the top of an async function to mark the function as a Server Action, or at the top of a separate file to mark all exports of that file as Server Actions. (Source: Next.js Docs (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#convention))