I'm making a simple file upload system with multer:
var maxSize = 1 * 1000 * 1000; var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, 'public/upload'); }, filename: function (req, file, callback) { callback(null, file.originalname); }, onFileUploadStart: function(file, req, res){ if(req.files.file.length > maxSize) { return false; } } }); var upload = multer({ storage : storage}).single('bestand'); router.post('/upload',function(req,res){ upload(req,res,function(err) { if(err) { return res.end("Error uploading file."); } console.log(req.file); res.redirect(req.baseUrl); }); });
This all works fine and the file gets uploaded. The only thing that is not working is the limit on the max size. I made it so that onfileupload start the size of the file gets checked and if its to big it will return false. But the file still just gets uploaded.
It seems that onFileUploadStart
isn't doing anything at all. I tried to console.log
something in it, but nothing.
What am I doing wrong? How can I limit the file size when uploading with multer?
The memoryStorage is mainly for handling the file buffer in a temporary way. example : you want to receive small files and relay them to another server which stores the media. ( multer receives stores in memory temp, relays and frees the memory by itself once theres no reference to it anymore)
Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form. Basic usage example: Don't forget the enctype="multipart/form-data" in your form.
Uploading multiple files with Multer is similar to a single file upload, but with a few changes. The upload. array method accepts two parameters, which are the required field name myFiles and the maximum count of files 12 .
There is no onFileUploadStart
with the new multer
API. If you want to limit the file size, you should instead add limits: { fileSize: maxSize }
to the object passed to multer()
:
var upload = multer({ storage: storage, limits: { fileSize: maxSize } }).single('bestand');
I think it is you are looking. Have a great day.
const fileFilter = (req, file, cb) => { const fileSize = parseInt(req.headers['content-length']); if((file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg' || file.mimetype === 'application/octet-stream') && (fileSize <= 1282810)) { cb(null, true); } else if(file.mimetype === 'video/mp4' && fileSize <= 22282810) { cb(null, true); } else { cb(null, false); }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With