|
1 |
| -import { put } from '@vercel/blob' |
| 1 | +import { handleUpload, type HandleUploadBody } from '@vercel/blob/client' |
2 | 2 | import { NextResponse } from 'next/server'
|
3 |
| -import { customAlphabet } from 'nanoid' |
4 | 3 |
|
5 |
| -export const runtime = 'edge' |
| 4 | +export async function POST(request: Request): Promise<NextResponse> { |
| 5 | + const body = (await request.json()) as HandleUploadBody |
6 | 6 |
|
7 |
| -const nanoid = customAlphabet( |
8 |
| - '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', |
9 |
| - 7 |
10 |
| -) // 7-character random string |
11 |
| -export async function POST(req: Request) { |
12 |
| - const file = req.body || '' |
13 |
| - const contentType = req.headers.get('content-type') || 'text/plain' |
14 |
| - const filename = `${nanoid()}.${contentType.split('/')[1]}` |
15 |
| - const blob = await put(filename, file, { |
16 |
| - contentType, |
17 |
| - access: 'public', |
18 |
| - }) |
| 7 | + try { |
| 8 | + const jsonResponse = await handleUpload({ |
| 9 | + body, |
| 10 | + request, |
| 11 | + onBeforeGenerateToken: async () => |
| 12 | + // pathname |
| 13 | + // clientPayload |
| 14 | + { |
| 15 | + // Generate a client token for the browser to upload the file |
| 16 | + // ⚠️ Authenticate and authorize users before generating the token. |
| 17 | + // Otherwise, you're allowing anonymous uploads. |
| 18 | + return { |
| 19 | + allowedContentTypes: ['image/*'], |
| 20 | + maximumSizeInBytes: 50 * 1024 * 1024, // 50MB |
| 21 | + } |
| 22 | + }, |
| 23 | + onUploadCompleted: async ({ blob, tokenPayload }) => { |
| 24 | + // Get notified of client upload completion |
| 25 | + // ⚠️ This will not work during development (localhost), |
| 26 | + // Unless you use ngrok or a similar service to expose and test your local server |
| 27 | + console.log('blob upload completed', blob, tokenPayload) |
| 28 | + }, |
| 29 | + }) |
19 | 30 |
|
20 |
| - return NextResponse.json(blob) |
| 31 | + return NextResponse.json(jsonResponse) |
| 32 | + } catch (error) { |
| 33 | + return NextResponse.json( |
| 34 | + { error: (error as Error).message }, |
| 35 | + { status: 400 } // The webhook will retry 5 times waiting for a 200 |
| 36 | + ) |
| 37 | + } |
21 | 38 | }
|
0 commit comments