5

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

4 Answers 4

5
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.

Sign up to request clarification or add additional context in comments.

1 Comment

I recommend refraining from using code snippets when running them does not introduce any utility to the answer, such as when there is no console logs and no visible elements.
2

In my case, it was the nginx configuration that cause the blocking (1MB body size in default).

Adding this one line of code in my nginx website config fix the problems.

 Server{ 

    client_max_body_size 200M;
    *...my website configs*

  }

For more details: https://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size

Comments

1

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/

Comments

0

By default, the maximum size of the request body sent to a Server Action is 1MB, to prevent the consumption of excessive server resources in parsing large amounts of data, as well as potential DDoS attacks.

However, you can configure this limit using the serverActions.bodySizeLimit option. It can take the number of bytes or any string format supported by bytes, for example 1000, '500kb' or '3mb'.

// next.config.js

/** @type {import('next').NextConfig} */
 
module.exports = {
  experimental: {
    serverActions: {
      bodySizeLimit: '2mb',
    },
  },
}

source: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions

1 Comment

thank you but even with this added, it throws error 413. I'm using graphql-yoga and next, and i set the bodySizeLimit to '100mb', tried also 100000000

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.