Accessing form fields before a custom storage engine
- Dominant language
- JavaScript
- Stars
- 12.1k
- Forks
- 1.1k
- Avg merge
- 8d 2h
- Merged PRs (30d)
- 21
Description
I'm currently using Multer with a custom storage engine that uploads a file to a location specified in the request. I'm currently getting the destination and a couple other parameters from the query, but I'd prefer to consolidate all input data into the form data. This destination input requires some extra validation that needs access to `res` and `next`. The current implementation is as follows:
```
upload(req, res, next) {
// Ideally this would be `req.body.destination`;
const destination = req.query.destination;
/* Validation ... */
return multer({
storage: new CustomStorage(destination),
}).single('file')(req, res, next);
}
```
However, Multer needs to run before this validation in order to parse the form data into `req.body` in the first place. I attempted to solve this by running a second Multer instance before the storage engine -- this instance would ignore the files and parse any text fields into `req.body`. The implementation was as follows:
```
multer({
fileFilter: (req, file, cb) => { return cb(null, false); },
}).any();
```
Running this did allow me to access the form data in `req.body` in the upload middleware, but then I received the following error:
```
Error: Unexpected end of form
at Multipart._final (/Users/robert/bucket/node_modules/busboy/lib/types/multipart.js:588:17)
at callFinal (node:internal/streams/writable:694:27)
at prefinish (node:internal/streams/writable:723:7)
at finishMaybe (node:internal/streams/writable:733:5)
at Multipart.Writable.end (node:internal/streams/writable:631:5)
at onend (node:internal/streams/readable:693:10)
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
storageErrors: []
}
```
I attempted to downgrade to Multer 1.4.3 after reading [issue 1144](https://github.com/expressjs/multer/issues/1144), and doing so did stop the error, but resulted in the API route erroring out with a `400` status and no error message instead.
How can I access the form data fields here?
Contributor guide
Assessment
This issue has not been assessed yet.