1.1.7 • Published 6 months ago

common-file-upload v1.1.7

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

Common File Upload Middleware

This is a Node.js middleware for handling file uploads, built on top of Express.js. It allows you to upload files with configurable validation and save them to a specified directory.

Features

  • Flexible Configuration: Define multiple file upload fields with specific rules.
  • Validation Support: Enforce file types, number of files, and required fields.
  • Easy Integration: Plug-and-play middleware for Express.js applications.

Installation

Install the middleware using npm:

npm install common-file-upload

Usage example with detailed comments

Middleware using Express:

import { fileUpload, fileRead } from "common-file-upload";
import express from "express";

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// File upload configuration
const uploadConfig = [
	{
		field: "file", // The field name in the form-data
		uploadPath: "./uploads", // Directory to save the uploaded files
		validation: {
			required: true,
			min: 1,
			max: 5, // Maximum 5 files for this field
			filter: ["image/jpeg", "image/png"] // Allowed MIME types
		}
	}
];

// Define a route with file upload
app.post("/upload", fileUpload(uploadConfig), (req, res) => {
	// Access uploaded files
	const files = req.files;

	res.json({
		message: "Files uploaded successfully!",
		files
	});
});

// File read configuration
const readConfig = [
	{
		field: "file", // The field name in the form-data
		fileSize: 10 * 1024 * 1024, // Maximum file size: 10MB
		validation: {
			required: true,
			min: 1,
			max: 3, // Maximum 3 files for this field
			filter: ["application/pdf", "image/png"] // Allowed MIME types
		}
	}
];

// Define a route with file read
app.post("/read", fileRead(readConfig), (req, res) => {
	res.json({
		message: "Files read successfully!",
		files: req.files
	});
});

// Start the server
const PORT = 3030;
app.listen(PORT, () => {
	console.log(`Server is running on http://localhost:${PORT}`);
});

Example Usage of Custom response options (option) :

const option = {
	responses: {
		invalidField: {
			statusCode: 400,
			data: { success: false, message: "Unexpected file field or too many files uploaded." }
		},
		multerError: {
			statusCode: 500,
			data: { success: false, message: "File upload error occurred." }
		},
		requiredRes: {
			statusCode: 400,
			data: { success: false, message: "File is required." }
		},
		limitMin: {
			statusCode: 400,
			data: { success: false, message: "At least 1 file is required." }
		},
		limitMax: {
			statusCode: 400,
			data: { success: false, message: "Only 1 file is allowed." }
		}
	}
};

fileUpload(uploadConfig, option);

Pass the option object when calling the fileUpload function:

import { fileUpload, fileRead } from "common-file-upload";

app.post("/upload", fileUpload(uploadConfig, option), (req, res) => {
	// Access uploaded files
	const files = req.files;

	res.json({
		message: "Files uploaded successfully!",
		files
	});
});

Configuration Options

The middleware accepts an array of configurations for each file upload field:

Field Configuration

OptionTypeDescription
fieldstringThe name of the form-data field for the file.
uploadPathstringDirectory path where the uploaded files will be saved.
validationobjectValidation rules for the file upload (see below).

Validation Rules

OptionTypeDescription
requiredbooleanWhether the field is required.
minnumberMinimum number of files to upload.
maxnumberMaximum number of files to upload.
filterstring[]Array of allowed MIME types (e.g.., image/jpeg, image/png).

Custom Response Options (option)

You can also define custom responses for various error scenarios such as invalid file fields, Multer errors, or required files not being uploaded. These responses are passed as an option object to the fileUpload middleware.

option Object

The option object contains custom responses for different error conditions:

OptionTypeDescription
responsesobjectCustom response configurations for errors.
invalidFieldobjectResponse when an unexpected file field or too many files are uploaded.
multerErrorobjectResponse for general Multer errors such as file size limits or disk errors.
requiredResobjectResponse when a required file is not uploaded.
limitMinobjectResponse when the number of uploaded files is less than the minimum.
limitMaxobjectResponse when the number of uploaded files exceeds the maximum allowed.

API Reference

fileUpload(config)

Parameters:

  • config (Array): An array of file upload configurations.
  • option (Object, Optional): An object containing custom error responses.

fileRead(config, option)

Parameters:

  • config (Array): An array of file upload configurations.
  • option (Object, Optional): An object containing custom error responses.

Returns:

  • Middleware function for handling file uploads.

License

This project is licensed under the MIT License.

1.1.7

6 months ago

1.1.1

8 months ago

1.1.0

8 months ago

1.1.0-lts.2

8 months ago

1.1.0-lts.3

8 months ago

1.0.9

8 months ago

1.0.8

8 months ago

1.1.6

8 months ago

1.0.7

8 months ago

1.1.5

8 months ago

1.1.1-lts.1

8 months ago

1.0.6

8 months ago

1.1.4

8 months ago

1.1.1-lts-1

8 months ago

1.1.0-lts.1

8 months ago

1.0.5

8 months ago

1.1.3

8 months ago

1.0.4

8 months ago

1.1.2

8 months ago

1.0.3

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago