Search code examples
reactjsexpressbackendmulter

Can't upload more than 1mb on multer with react js


I am just trying to upload simple PDF docs to my express server. The file about 800kb.

However when I run my upload code I get an upload file is too large error.

  expected: 833561,
  length: 833561,
  limit: 102400,
  type: 'entity.too.large'

So I did my research and saw everyone recommending I up my max file size using the lines

let maxSize = 1024 * 1024 * 10

const uploadStorage = multer({ storage: storage, limits: { fieldSize: maxSize } })

However no matter what number I change it too I still get the file too large error. I have tried changing the number and the fieldSize property with no luck.

Here is the main chunk of the backend:

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    console.log('QQQQQQQQQQQQQQQQQQQQ');
    cb(null, "uploads/")
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + "-" + file.originalname)
  },
})

let maxSize = 1024 * 1024 * 10

const uploadStorage = multer({ storage: storage, limits: { fieldSize: maxSize } })

// Single file
app.post("/upload/single", uploadStorage.single("file"), (req, res) => {
  console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');
  console.log(req.file)
  // return res.send("Single file")
})

And a very simple front end upload... yes I confirm the file is uploaded to the front end .

  const onFileUpload = () => {
    console.log("BBBBBBBBBBBBBBBBBB");
    const formData = new FormData();

    formData.append("File", selectedFile);

    client
      .postPdf("http://localhost:4000/upload/single", selectedFile, false)
      .then((res) => {
        console.log("res", res.data);
      })

      .catch((err) => {
        console.error("Unable to post PDF", err);
      });
  };

There are loads of pages saying the filesize change should of worked but I still get an error of file too large. I will only ever be uploading PDF and never likely to be more than a few mb.

Does anyone know how to fix the file size or another method of uploading files to the backend?

I have tried adjusting the variables for filesize and storage.


Solution

  • I think your issue is not related to multer, so if your backend is in express, try to set express body limit

    app.use(express.json({ limit: '10mb' }));