Skip to content

Instantly share code, notes, and snippets.

@extsalt
Last active February 12, 2023 05:29
Show Gist options
  • Save extsalt/d7d6f8ebb61aea0228a2bc327619653a to your computer and use it in GitHub Desktop.
Save extsalt/d7d6f8ebb61aea0228a2bc327619653a to your computer and use it in GitHub Desktop.
formidable nextjs file upload
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