npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

file-uploader-express

v1.1.12

Published

A Node.js package for handling file uploads with support for various file types

Downloads

105

Readme

file-uploader

A robust Node.js package for handling file uploads with support for various file types, designed to integrate seamlessly with Express.js applications.

Table of Contents

Features

  • 📁 Supports multiple file types: JPEG, PNG, PDF, DOC, DOCX, MP3, and MP4
  • 🆔 Generates unique filenames using UUID
  • 🗂️ Organizes uploaded files into type-specific directories
  • 🔢 Handles single and multiple file uploads
  • ⚠️ Built-in error handling and validation
  • 🔒 File size limit enforcement
  • 🛠️ Customizable upload directory

Installation

npm install file-uploader-express

Requirements

  • Node.js >= 12.0.0
  • Express.js >= 4.17.1
  • express-fileupload >= 1.2.1

Usage

Uploading Files

When sending a file upload request to your server, include the file in the request body with the key 'file'. This key is currently hardcoded in the implementation.

For example, if you're using a form:

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="Upload">
</form>

When using JavaScript to send the request:

const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('/upload', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});

CommonJS

const express = require('express');
const fileUpload = require('express-fileupload');
const { uploadFile } = require('file-uploader-express');

const app = express();

app.use(fileUpload());

app.post('/upload', async (req, res) => {
  try {
    const result = await uploadFile(req, res);
    res.json(result);
  } catch (error) {
    res.status(500).json({ message: error.message, success: false });
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

ES6 Module

import express from 'express';
import fileUpload from 'express-fileupload';
import { uploadFile } from 'file-uploader-express';

const app = express();

app.use(fileUpload());

app.post('/upload', async (req, res) => {
  try {
    const result = await uploadFile(req, res);
    res.json(result);
  } catch (error) {
    res.status(500).json({ message: error.message, success: false });
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Configuration

You can configure the file upload behavior using environment variables or by passing options to the uploadFile function:

  • BASE_URL: Set the base URL for the uploaded files. If not set, it defaults to the relative path.
  • UPLOAD_BASE_DIR: Set the base upload directory. If not set, it defaults to './public'.

Example using environment variables:

BASE_URL=https://example.com/uploads
UPLOAD_BASE_DIR=/path/to/uploads

Example passing options to uploadFile:

const result = await uploadFile(req, res, {
  uploadBaseDir: '/custom/upload/path',
  maxFileSize: 10 * 1024 * 1024 // 10MB
});

API Reference

uploadFile(req, res, options)

Handles file upload(s) from a multipart form data request.

Parameters

  • req (Object): Express request object
  • res (Object): Express response object
  • options (Object, optional):
    • uploadBaseDir (String): Base directory for uploads (default: process.env.UPLOAD_BASE_DIR || './public')
    • maxFileSize (Number): Maximum file size in bytes (default: 5MB)

Returns

Promise that resolves to an object with the following structure:

{
  message: String,
  success: Boolean,
  body: {
    uploadedFiles: String | Array
  }
}

For single file uploads, uploadedFiles will be a string. For multiple file uploads, it will be an array of strings.

Supported File Types

  • Images: JPEG, PNG
  • Documents: PDF, DOC, DOCX
  • Audio: MP3
  • Video: MP4

Error Handling

The package includes built-in error handling for common issues:

  • NO_FILE: No file was uploaded
  • FILE_TOO_LARGE: File size exceeds the specified limit
  • INVALID_FILE_TYPE: Uploaded file type is not supported

If an error occurs, the function will return an object with success: false and details about the error.

Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page if you want to contribute.

  1. Fork the project
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

This project is licensed under the ISC License.

Author

Vijay Sharma


For any questions or support, please open an issue in the GitHub repository.