Woodsy
Woodsy

Reputation: 3377

Express Multer does not work when using node version 14.15.1

I have the following snippet of code:

var fileUpload = multer({
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
     cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
     cb(null, Date.now() + file.originalname)
    }
 })
});

router.post("/addFile", fileUpload.single('newFile'), function (req, res) {
  let _id = req.body.someId;
  console.log("Adding File with id: " + _id);
  // some database inserts and response
  ...

This code works 100% fine in node v12. I can upload files of any size, however once I change to node v14.15.1 the upload behaves odd for anything larger than about 60KB. Looking at the file system I can see the upload worked however nothing inside the route was executed. So I can see the file on the filesystem but that console.log and any database commands won't execute.

Looking at the request I never appear to get back a response header for files larger than 60KB on node 14. I assume not getting a response header to my request is why the upload is failing.

The following is the javascript that performs the file upload.

var formData = new FormData();
formData.append('newFile', $("#newFile")[0].files[0]);
formData.append('someId', $('#someId').val());

$.ajax({
   url: './addFile',
   data: formData,
   contentType: false,
   processData: false,
   type: 'POST',
   success: function (data) {
     console.log('success upload')
}); 

I found the cause of the problem but don't know of a fix. The if I set res.local the upload fails. If I comment it out the upload will work. Does anyone know of a fix/workaround for this:

app.use(function (req, res, next) {
  req.connection = mysqlConnection;
  res.locals = {
    version: '1'
  };
  next();
});

app.use('/', indexRouter);

Upvotes: 0

Views: 517

Answers (2)

Ncifra
Ncifra

Reputation: 673

Your two lines of code:

  req.connection = mysqlConnection;
  res.locals = {
    version: '1'
  };

should be avoided because both req.connection and res.locals are sort of reserved objects in express, the first contains connection data, like IP and other headers, while the second should be used for variables scoped to the current request. Depending on what else you are doing in the code, you are overwriting these two, and most likely breaking something that in this case shows as a bug in multer. You have fixed the req.connection problem, but still you may break other middleware/functions that use res.locals, so instead of reinitializing it like you do, you can just add your own property like:

res.locals.version = '1'

Upvotes: 1

Woodsy
Woodsy

Reputation: 3377

I changed req.connection to req.dbconn this seemed to have fixed the issue.

app.use(function (req, res, next) {
   req.dbconn = mysqlConnection
   res.locals = {
      version: 'version'
   };
   next();
});

Upvotes: 0

Related Questions