简体   繁体   中英

Next.js: Error 413 Request Entity Too Large on file upload

I'm having troubles trying to upload large files with Next.js. I've created an onChange function on my input file, here's the code:

const handleFileUpload = () => new Promise(async (resolve) => {
    if(ref.current?.files){
        const formData = new FormData()
        Object.entries(ref.current.files).map(([i, f]) => {
            return formData.append(`${id}_${i}`, f)
        })

        const config = {
            headers: { 'content-type': 'multipart/form-data' },
            onUploadProgress: (event) => {
                const p = Math.round((event.loaded * 100) / event.total);
                setProgress(p)
            }
        }

        try{
            const response = await axios.post('/api/upload-file', formData, config);
            resolve(response)
        }
        catch(err){
            console.log(err)
        }
   }
}

And this is my /api/upload-file.js

import nextConnect from 'next-connect';
import multer from 'multer';
import { METHOD_NOT_ALLOWED, NOT_IMPLEMENTED, OK } from '../../utils/statusCode';

const upload = multer({

    storage: multer.diskStorage({
        destination: './public/upload',
        filename: (req, file, cb) => cb(null, file.originalname),
    })

})

const apiRoute = nextConnect({

    onError(error, req, res){
        res.status(NOT_IMPLEMENTED).json({error: `Errore: impossibile procedere. ${error.message}`})
    },
    onNoMatch(req, res){
        res.status(METHOD_NOT_ALLOWED).json({error: `Metodo ${req.method} non permesso`})
    }

})

apiRoute.use(upload.any())
apiRoute.post((req, res) => res.status(OK).json({data: 'success'}))

export default apiRoute

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

It works perfectly with small files, but I receive a 413 error with larger ones (even 1 or 2MB), is there something I'm missing here?

I'm using Next.js 12.0.3

I struggled with this error for almost two days. And, I solved it finally. During file upload, server requires a boundary where your file-data ends.

The trick is to use a "unique boundary" marker

The code should be used is:

await axios.post(
    url,
    filedataObj,
    {
        headers: {
            ...fileToUpload.getHeaders(),
            //some other headers
        },
    }
);

See https://www.gyanblog.com/javascript/next.js-solving-request-entity-too-large-issue-413/

export const config = {
  api: {
    bodyParser: {
      sizeLimit: '20mb',
    },
  },
};

Add this to the api route that you are uploading files to and it will fix the problem.

Found the issue and solved the problem after fixing nginx settings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM