Unverified Commit 2e858062 authored by su's avatar su Committed by GitHub

feat(examples): add upload file example with Server Actions (#58467)

Add upload file example with Server Actions
parent 1f3178e7
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Upload file with Next.js and Server Actions
This example shows how you can build upload forms with Next.js and Server Actions.
## Deploy your own
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/server-actions-upload&project-name=server-actions-upload&repository-name=server-actions-upload)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example server-actions-upload next-upload-app
```
```bash
yarn create next-app --example server-actions-upload next-upload-app
```
```bash
pnpm create next-app --example server-actions-upload next-upload-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
'use server'
import fs from 'fs'
import path from 'path'
import { promisify } from 'util'
const writeFile = promisify(fs.writeFile)
export async function saveData(formData: FormData) {
const file = formData.get('file') as File
const fileBuffer = await file.arrayBuffer()
const filePath = path.join(`/tmp/${file.name}`)
await writeFile(filePath, Buffer.from(fileBuffer))
const payload = {
email: formData.get('email'),
}
console.log('payload', payload)
return payload
}
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
)
}
import UploadForm from './upload-form'
export default function Home() {
return <UploadForm />
}
'use client'
import { useFormStatus } from 'react-dom'
import { saveData } from './action'
import { useRef } from 'react'
function Submit() {
const { pending } = useFormStatus()
return <button disabled={pending}>{pending ? 'Submitting' : 'Submit'}</button>
}
export default function UploadForm() {
const formRef = useRef<HTMLFormElement | null>(null)
async function formAction(formData: FormData) {
await saveData(formData)
formRef.current?.reset()
alert('Save success!')
}
return (
<form action={formAction} ref={formRef}>
<h1>Upload Demo</h1>
<div>Email</div>
<input type="email" name="email" required />
<br />
<br />
<div>Select file</div>
<input type="file" name="file" required />
<br />
<br />
<br />
<Submit />
</form>
)
}
/** @type {import('next').NextConfig} */
const nextConfig = {}
module.exports = nextConfig
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "latest"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18"
}
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
},
"forceConsistentCasingInFileNames": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment