1.5.0 • Published 3 years ago

multer-sc v1.5.0

Weekly downloads
3
License
ISC
Repository
-
Last release
3 years ago

Multer (with) Size Check

This is same package as Multer except it has a dynamic check for file size. You can check multer here multer.

NOTE: Multer works with fileStreams which make it hard for developers to check and apply file size checks and limits.

Installation

$ npm install --save multer-sc

Usage

To understand more about multer-sc, let's take an example. Let's say there is a software that has more than one type of users and file upload limit varies for each user type. Let's say admins can upload upto 50MB of files where normal user can upload max of 2MB. In standard multer package, it was near to impossible to apply dynamic check for both.

fileSizeHook:

In this method, you will get relevant meta-data field sent along with post request. Call this callback fileUploadLimit and provide the limit in bytes. And that is basically it.

It would look something like this:

var uploadFiles = multer({
	storage: storageUploads,
	fileFilter: async function(req, file, callback) {
		...
	},
	limits: {
		...
	},
	sizeInfoHook: async function(options){
		var { email } = options.data;
		var user = await User.findOne({ email: email });
		options.cb.fileUploadLimit(imageUploadLimits[user.globalRank]);
	}
});

Multer instance also holds copy of file upload limit. In case of example above, uploadFiles.fieldData['ful'] will contain the file upload limit passed in bytes.

Client Side Measures

How to Request?

For multer-sc to work smoothly in your project, please make sure that you send releveant data such as username, token, email, etc first and then adding the actual file. Appending the meta-data first will make it available in the fileSizeHook handler.

Example is given below:

    var payload = new FormData();

	//add meta-data first
    payload.append('email', email);
    payload.append('username', username);

	//and then the actual file (image, video, etc)
	payload.append('imageFile', InputFile.current.files[0]);

    axios
      .post(API_EP + '/upload', payload, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
      .then((response) => {
		...
	  }