Last active
February 12, 2023 05:29
-
-
Save extsalt/d7d6f8ebb61aea0228a2bc327619653a to your computer and use it in GitHub Desktop.
formidable nextjs file upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextApiRequest, NextApiResponse } from 'next'; | |
import formidable from 'formidable'; | |
export const config = { | |
api: { | |
bodyParser: false, // disable nextjs body parsing | |
}, | |
}; | |
// /post/api/upload.ts | |
export default async function handle( | |
request: NextApiRequest, | |
response: NextApiResponse | |
) { | |
const form = formidable(); | |
form.parse(request, function (err, fields, files) { | |
// handle any error occure while parsing request | |
if (err) { | |
response | |
.status(400) | |
.json({ messsage: 'Something excepted happened, please try again.' }); | |
return; | |
} | |
response.json({ | |
...fields, | |
...files, | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment