Skip to content

prakashbahadurchand/nestjs-file-handling

Repository files navigation

NestJS File Handling

A comprehensive example of file handling (upload, download, stream, delete, update) in a NestJS application. This project demonstrates best practices for managing files, including categorization, public URL generation, and robust error handling, all documented with Swagger.

Features

  • File Upload: Supports various file types. Files are automatically categorized (images, documents, audio, video, others) based on MIME type and stored with a unique, prefixed filename.
  • File Download: Allows users to download stored files.
  • File Streaming: Enables direct preview/streaming of supported file types in the browser.
  • File Deletion: Provides an endpoint to remove files from a specific category.
  • File Update: Allows replacing an existing file with a new one.
  • File Listing: Endpoint to list all uploaded files with their details.
  • File Information: Retrieve metadata (category, path, MIME type) for a specific file by its name.
  • Categorized Storage: Files are stored in categorized subdirectories within the uploads folder (e.g., uploads/images, uploads/videos).
  • Swagger API Documentation: Integrated for easy API testing and exploration (available at /api).
  • Public Preview/Access Links: Generates shareable URLs for uploaded files.
  • Standardized API Responses: Consistent JSON response format for success and error messages.

Prerequisites

  • Node.js (version specified in package.json or latest LTS)
  • npm or yarn

Getting Started

  1. Clone the repository: If you haven't cloned it yet:

    git clone <repository-url>
    cd nestjs-file-handling
  2. Install dependencies:

    npm install

    Alternatively, if you use yarn:

    yarn install
  3. Run the application:

    npm run start:dev

    The application will start in development mode with hot-reloading. By default, it runs on http://localhost:3000.

  4. Access the API Documentation: Navigate to http://localhost:3000/api in your browser to access the Swagger UI. This interface allows you to explore and test all available API endpoints.

API Endpoints

The base URL for all API endpoints is http://localhost:3000.

Method Endpoint Description
POST /files/upload Uploads a new file. The file is categorized and stored.
GET /files/list Lists all uploaded files with their details.
GET /files/stream/:category/:filename Streams a file for inline viewing (e.g., in browser).
GET /files/download/:category/:filename Downloads a file as an attachment.
GET /files/by-name/:filename/stream Streams a file by its name (searches across all categories).
GET /files/by-name/:filename/download Downloads a file by its name (searches across all categories).
GET /files/info/:filename Retrieves information (path, category, MIME type) about a file by its name.
PUT /files/update/:category/:filename Updates an existing file by replacing it with a new one.
DELETE /files/delete/:category/:filename Deletes a specific file from a category.

Example: Uploading a File

Use a tool like curl or an API client like Postman to upload a file.

Using cURL:

curl -X POST http://localhost:3000/files/upload \
  -F 'file=@/path/to/your/file.jpg'

Replace /path/to/your/file.jpg with the actual path to your file.

Response Example (Success):

{
  "statusCode": 201,
  "message": "File uploaded successfully.",
  "data": {
    "filename": "img-file-YYYYMMDDHHMMSS.jpg",
    "category": "images",
    "url": "http://localhost:3000/files/stream/images/img-file-YYYYMMDDHHMMSS.jpg",
    "originalName": "file.jpg",
    "mimeType": "image/jpeg"
  }
}

(Note: YYYYMMDDHHMMSS in the filename represents the timestamp of when the file was uploaded.)

Project Structure

.
├── uploads/              # Directory where uploaded files are stored (categorized)
│   ├── audios/
│   ├── documents/
│   ├── images/
│   ├── others/
│   └── videos/
├── src/
│   ├── files/            # Module for file handling logic
│   │   ├── dto/          # Data Transfer Objects for files
│   │   ├── files.controller.ts
│   │   ├── files.handler.ts # Helper functions for file processing
│   │   ├── files.module.ts
│   │   └── files.service.ts
│   ├── app.module.ts     # Root application module
│   └── main.ts           # Application entry point
├── .gitignore
├── eslint.config.mjs
├── package.json
├── tsconfig.json
└── README.md

Key Dependencies

  • NestJS (@nestjs/common, @nestjs/core, @nestjs/platform-express): A progressive Node.js framework for building efficient, reliable and scalable server-side applications.
  • Multer (multer): Middleware for handling multipart/form-data, primarily used for uploading files.
  • Swagger (@nestjs/swagger, swagger-ui-express): For API documentation and UI.
  • class-validator, class-transformer: For request validation and transformation.

Available Scripts

Refer to the scripts section in the package.json file for all available commands. Key scripts include:

  • npm run start:dev: Starts the application in development mode with watch enabled.
  • npm run build: Compiles the TypeScript application to JavaScript.
  • npm run start:prod: Runs the built application (suitable for production).
  • npm run lint: Lints the codebase using ESLint.
  • npm run format: Formats the code using Prettier.
  • npm test: Runs Jest unit tests.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request with improvements or new features.

License

This project is licensed under the MIT License (as specified in package.json).

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published