CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-multer

Node.js middleware for handling multipart/form-data, primarily used for file uploads

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

core-middleware.mddocs/

Core Middleware

Primary multer functionality for creating upload middleware instances with different upload strategies and configuration options.

Capabilities

Multer Factory Function

Creates a multer instance configured with the specified options.

/**
 * Creates a multer instance with the given configuration options
 * @param options - Configuration object for upload behavior
 * @returns MulterInstance with middleware methods
 */
function multer(options?: MulterOptions): MulterInstance;

interface MulterOptions {
  /** Destination directory (shorthand for diskStorage) */
  dest?: string;
  /** Storage engine instance */
  storage?: StorageEngine;
  /** Upload limits configuration */
  limits?: LimitsOptions;
  /** Keep full file paths instead of just basename */
  preservePath?: boolean;
  /** Function to control which files are accepted */
  fileFilter?: (req: Request, file: File, cb: FileFilterCallback) => void;
}

Usage Examples:

const multer = require('multer');

// Simple configuration with destination directory
const upload = multer({ dest: 'uploads/' });

// Advanced configuration with custom storage and limits
const upload = multer({
  storage: multer.diskStorage({
    destination: './public/uploads',
    filename: (req, file, cb) => {
      cb(null, Date.now() + '-' + file.originalname);
    }
  }),
  limits: {
    fileSize: 1024 * 1024 * 5, // 5MB limit
    files: 3 // Maximum 3 files
  },
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('Only image files allowed'), false);
    }
  }
});

Single File Upload

Accept a single file with the specified field name.

/**
 * Creates middleware to handle single file upload
 * @param fieldname - Name of the form field containing the file
 * @returns Express middleware function
 */
single(fieldname: string): RequestHandler;

Usage Examples:

// HTML form
// <form action="/profile" method="post" enctype="multipart/form-data">
//   <input type="file" name="avatar" />
// </form>

app.post('/profile', upload.single('avatar'), (req, res) => {
  if (req.file) {
    console.log('File uploaded:', req.file.originalname);
    console.log('File size:', req.file.size);
    console.log('File path:', req.file.path);
  }
  res.send('Upload successful');
});

Array File Upload

Accept an array of files with the same field name, optionally limiting the count.

/**
 * Creates middleware to handle multiple files with same field name
 * @param fieldname - Name of the form field containing the files
 * @param maxCount - Maximum number of files to accept (optional)
 * @returns Express middleware function
 */
array(fieldname: string, maxCount?: number): RequestHandler;

Usage Examples:

// HTML form
// <form action="/photos" method="post" enctype="multipart/form-data">
//   <input type="file" name="photos" multiple />
// </form>

app.post('/photos', upload.array('photos', 12), (req, res) => {
  if (req.files && req.files.length > 0) {
    console.log(`Uploaded ${req.files.length} files`);
    req.files.forEach((file, index) => {
      console.log(`File ${index + 1}:`, file.originalname);
    });
  }
  res.send('Upload successful');
});

Mixed Field Upload

Accept multiple files with different field names and individual count limits.

/**
 * Creates middleware to handle files from multiple form fields
 * @param fields - Array of field configurations with names and limits
 * @returns Express middleware function
 */
fields(fields: FieldConfig[]): RequestHandler;

interface FieldConfig {
  name: string;
  maxCount?: number;
}

Usage Examples:

// HTML form
// <form action="/profile" method="post" enctype="multipart/form-data">
//   <input type="file" name="avatar" />
//   <input type="file" name="gallery" multiple />
// </form>

const uploadFields = upload.fields([
  { name: 'avatar', maxCount: 1 },
  { name: 'gallery', maxCount: 8 }
]);

app.post('/profile', uploadFields, (req, res) => {
  if (req.files) {
    // req.files is an object with fieldname as key
    if (req.files['avatar']) {
      console.log('Avatar:', req.files['avatar'][0].originalname);
    }
    if (req.files['gallery']) {
      console.log(`Gallery: ${req.files['gallery'].length} images`);
    }
  }
  res.send('Upload successful');
});

Text-Only Upload

Accept only text fields, rejecting any file uploads.

/**
 * Creates middleware that accepts only text fields, no files
 * @returns Express middleware function that rejects file uploads
 */
none(): RequestHandler;

Usage Examples:

// For forms that should only contain text data
app.post('/contact', upload.none(), (req, res) => {
  // Only req.body will be populated with text fields
  console.log('Name:', req.body.name);
  console.log('Email:', req.body.email);
  console.log('Message:', req.body.message);
  res.send('Message received');
});

Any File Upload

Accept all files sent over the wire, regardless of field name.

/**
 * Creates middleware that accepts any files from any field
 * @returns Express middleware function that accepts all files
 */
any(): RequestHandler;

Usage Examples:

// WARNING: Use with caution - accepts files from any field
app.post('/upload-anything', upload.any(), (req, res) => {
  if (req.files && req.files.length > 0) {
    console.log(`Received ${req.files.length} files from various fields`);
    req.files.forEach(file => {
      console.log(`Field: ${file.fieldname}, File: ${file.originalname}`);
    });
  }
  res.send('Upload successful');
});

Configuration Details

Limits Configuration

interface LimitsOptions {
  /** Max field name size in bytes (default: 100) */
  fieldNameSize?: number;
  /** Max field value size in bytes (default: 1MB) */
  fieldSize?: number;
  /** Max number of non-file fields (default: Infinity) */
  fields?: number;
  /** Max file size in bytes (default: Infinity) */
  fileSize?: number;
  /** Max number of file fields (default: Infinity) */
  files?: number;
  /** Max number of parts (fields + files) (default: Infinity) */
  parts?: number;
  /** Max number of header key-value pairs (default: 2000) */
  headerPairs?: number;
}

File Filter Function

/**
 * Function to control which files should be uploaded
 * @param req - Express request object
 * @param file - File information object
 * @param cb - Callback to accept or reject the file
 */
type FileFilterFunction = (
  req: Request,
  file: File,
  cb: (error: Error | null, acceptFile: boolean) => void
) => void;

File Filter Examples:

// Accept only images
const imageFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('Only image files are allowed'), false);
  }
};

// Accept only specific file types
const documentFilter = (req, file, cb) => {
  const allowedTypes = ['application/pdf', 'application/msword', 'text/plain'];
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(null, false); // Silently reject
  }
};

// Size-based filtering (additional to limits)
const sizeFilter = (req, file, cb) => {
  // This example shows logic, but size filtering is better done via limits
  cb(null, true);
};

const upload = multer({
  dest: 'uploads/',
  fileFilter: imageFilter
});

docs

core-middleware.md

error-handling.md

index.md

storage-engines.md

tile.json