Skip to content

Instantly share code, notes, and snippets.

@agmm
Created January 31, 2020 23:03
Show Gist options
  • Save agmm/da47a027f3d73870020a5102388dd820 to your computer and use it in GitHub Desktop.
Save agmm/da47a027f3d73870020a5102388dd820 to your computer and use it in GitHub Desktop.
Simple Nextjs File Upload — Backend API
// Backend
import formidable from 'formidable';
export const config = {
api: {
bodyParser: false,
},
};
export default async (req, res) => {
const form = new formidable.IncomingForm();
form.uploadDir = "./";
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
console.log(err, fields, files);
});
};
// For the frontend use:
// https://gist.github.com/AshikNesin/e44b1950f6a24cfcd85330ffc1713513
@iamtekeste
Copy link

Thank you! It worked flawlessly!

@agmm
Copy link
Author

agmm commented Apr 17, 2020

You're welcome

@ptcampbell
Copy link

ptcampbell commented Apr 29, 2020

Do you know why the images might look scrambled and corrupted, like they are tuned to a dead channel?

@waigel
Copy link

waigel commented May 14, 2020

@ptcampbell you can try to use formidable-serverless instead of formidable .
This works fine for me.

@surafell
Copy link

surafell commented Jun 6, 2020

Thank you very much, it works great!

@lukasweidich
Copy link

Thank you so much, worked really well! formidable-serverless was the right approach for me.

@mariokaram
Copy link

guys have you tried to deploy it to vercel and its still working ??

@gallirohik
Copy link

Thank you so much :)

@mirulnorazmi
Copy link

Thank you so Muchh!!!!!!!!!!!!!

@ketanip
Copy link

ketanip commented Jul 13, 2021

It worked like a charm, thank you.

@orpheousff8
Copy link

Thanks a ton! works like magic.

@automatejake
Copy link

I spent a stupid amount of time trying to figure this out until i stumbled upon this answer. Let me have your babies!!

@oelbaga
Copy link

oelbaga commented Feb 7, 2022

How do you reference the file and send it to AWS. I have all the implementation to send to AWS but I don't see how to reference the file itself that is received.

@damiano216
Copy link

damiano216 commented Dec 2, 2022

The above code works perfectly for me when passing some uploaded images from the NextJS frontend to the NextJS backend. However, for some other images, the backend code doesn't seem to be able to run.

Here is my code:

//FRONTEND
const form = new FormData();
form.append("file", file);

fetch("/api/myApiRouteFile", {
method: "POST",
body: form,
})
.then((res) => res.json())
.then((data) => {
console.log("data", data);
})
.catch((err) => {
console.log("err", err);
});

//Backend code in NextJS API route
import formidable from "formidable";

export const config = {
api: {
bodyParser: false,
},
};

const handler = async (req, res) => {
console.log("CODE RUNNING.... 🚀 "); //with some files, this message is not printed out, so I assume the code was not running. With other images however, everything is fine.

const form = new formidable.IncomingForm();
form.uploadDir = "./";
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
console.log(err, fields, files); //some images gets printed out, some other no.
});
};
export default handler;

Again, when uploading some images, the backend runs well and prints out the uploaded image file data, but for other images, nothing happens.

Does anyone know what could be the problem? Maybe a max file size?
Thanks for the help.

@VesperDev
Copy link

@damiano216 This is my code.

Frot-end

  const onUploadFile = async (file) => {
    const formData = new FormData()
    formData.append('file', file[0])
    fetch('/api/uploadfile', { method: 'POST', body: formData }).then((response) => {
      response.json().then(resuJ => {
        const { files } = resuJ
        onChangeEstudio('Imagen_studio', files.file.path)
      })
    })
  }

Backend

import formidable from 'formidable-serverless'

const uploadfile = async (req, res) => {
  if (req.method === 'POST') {
    return uploadfilePOST(req, res)
  } else {
    res.setHeader('Allow', ['POST'])
    res.status(405).end(`Method ${req.method} Not Allowed`)
  }

  async function uploadfilePOST (req, res) {
    const form = new formidable.IncomingForm()
    form.uploadDir = './public/estudios/'
    form.keepExtensions = true
    form.parse(req, (err, fields, files) => {
      if (err) res.status(500).send(err)
      res.status(200).json({ fields, files })
    })
  }
}

export const config = {
  api: {
    bodyParser: false
  }
}

export default uploadfile

That worked for me

@samipshah100
Copy link

samipshah100 commented May 16, 2023

@VesperDev thanks a lot it works. any chance you have tested if it works on work on a vercel.com production deployment?

@saket223
Copy link

@VesperDev Hi have you seen the error '413 Request entity too large' during this process?

@OscarJVD
Copy link

@damiano216 This is my code.

Frot-end

  const onUploadFile = async (file) => {
    const formData = new FormData()
    formData.append('file', file[0])
    fetch('/api/uploadfile', { method: 'POST', body: formData }).then((response) => {
      response.json().then(resuJ => {
        const { files } = resuJ
        onChangeEstudio('Imagen_studio', files.file.path)
      })
    })
  }

Backend

import formidable from 'formidable-serverless'

const uploadfile = async (req, res) => {
  if (req.method === 'POST') {
    return uploadfilePOST(req, res)
  } else {
    res.setHeader('Allow', ['POST'])
    res.status(405).end(`Method ${req.method} Not Allowed`)
  }

  async function uploadfilePOST (req, res) {
    const form = new formidable.IncomingForm()
    form.uploadDir = './public/estudios/'
    form.keepExtensions = true
    form.parse(req, (err, fields, files) => {
      if (err) res.status(500).send(err)
      res.status(200).json({ fields, files })
    })
  }
}

export const config = {
  api: {
    bodyParser: false
  }
}

export default uploadfile

That worked for me

do you have an alternative to upload videos and save them in s3?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment