1

I am using the mentioned fileuplaod middleware. I want to setup a middleware that warns on file size limit exceed but don't want to truncate the file.

app.use(fileUpload({
    limits: { fileSize: 1 * 1024 * 1024 },
    createParentPath: true,
    safeFileNames: true,
    preserveExtension: 5,
    limitHandler: function (req, res, next) {
        Logger.warn("File size limit has been exceeded");
    },
    abortOnLimit: false,
    useTempFiles: true,
    tempFileDir: './temp/apiuploads'
}));

The files are getting truncated. Hence the files that are uploaded cant be opened. I want to log the message when file size limit exceed but don't want to truncate the file. Please help me with a solution.

2
  • Can you show us a sample of your current output and your expected one, please? Commented Nov 24, 2019 at 9:52
  • I uploaded a pdf file of size 3mb. After upload the size of file became 1mb and as a result the file could not be opened. When I try to open that file it shows file cannot be opened. Commented Nov 30, 2019 at 7:16

1 Answer 1

2

Do not add file limits options for the middleware, also I recommend to use middleware only with upload routes.

Check uploaded file size after it has been uploaded with size value.

And log message if size more then your limit.

Example:

app.use('/upload', fileUpload({
    createParentPath: true,
    safeFileNames: true,
    preserveExtension: 5,
    useTempFiles: true,
    tempFileDir: './temp/apiuploads'
}));

app.post('/upload', (req, res) => {
  if (!req.files || Object.keys(req.files).length === 0) {
    res.status(400).send('No files were uploaded.');
    return;
  }

  const uploads = Object.values(req.files).map((file) => {
    if (file.size > 1 * 1024 * 1024) {
      Logger.warn(`File ${file.name} size limit has been exceeded`);
    }
    const uploadPath = path.join(__dirname, 'uploads', file.name);
    return file.mv(uploadPath);
  });

  Promise.all(uploads)
    .then(() => res.send('Files uploaded to ' + path.join(__dirname, 'uploads')))
    .catch(err => res.status(500).send(err));
});
Sign up to request clarification or add additional context in comments.

1 Comment

Please add code for everyone's use. And for clarity.

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.