Template - API
WelcomePrerequisitesNodeJS
  • Welcome!
    • About me
  • Prerequisites
    • Installation and Database Setup
    • Installing Node.js on the Server
  • NodeJS
    • 🆓Getting Started with the Free Template
    • 🎗️Premium Template - REST API
      • Structure
      • Middlewares and Guards
      • Core Modules
        • Prisma with NestJS
        • Swagger with NestJS
      • Dynamic Module
        • Create or Import Module
  • Modules
    • 🎗️Websockets
    • 🎗️Mailer
    • 🎗️Upload
Powered by GitBook
On this page
  • Key Features and Details
  • Placement in the Project
  • Installation
  • Environment Configuration
  • Available Upload Routes (Example)
  • Testing Upload Integration in Unity with C#
  • Extending the Upload Module
  1. Modules

Upload

This module provides easy and secure file uploading functionality to your Node.js application, designed for handling various file types and sizes with scalability in mind.

Warning: This module must be attached to an existing Node.js server, either the template we provide or a custom project from the user. However, it can only be attached to the Premium template due to the use of NestJS and TypeScript. If you already own the HTTPS Premium module, you can refer to the README to include only the necessary files and be guided on how to make calls to the WebSocket module.

Key Features and Details

The Upload module offers a reliable and customizable way to manage file uploads within your Node.js application. Below are the main features of the module:

  • File Uploading: Allows secure file uploads through HTTP POST requests, including validation for file type and size. Supports uploading multiple formats, ideal for profile pictures, documents, and other files.

  • Image Processing: Includes support for image processing using Sharp, with options to resize, reformat, and apply quality settings to images. This feature ensures images meet predefined standards, reducing server load and improving user experience.

  • Watermark Support: Optionally applies a watermark to uploaded images, allowing you to brand or secure image assets before saving them.

  • Storage Configuration: Configurable storage options via environment variables, including local storage and cloud-based services (such as Amazon S3). Environment variables such as UPLOAD_STORAGE_PATH and UPLOAD_MAX_FILE_SIZE make it easy to manage where files are stored and their size limitations.

  • Error Handling: Includes comprehensive error handling with informative logging and HTTP status responses, ensuring robust communication with clients if a file fails validation or cannot be saved.


Placement in the Project

This module should be placed in the following directory within the premium template project:

src/modules/upload

Installation

To get started, ensure you have the necessary dependencies installed:

npm install

If you haven't already, install Sharp for image processing:

npm install sharp

Environment Configuration

In the .env file, add the following configurations for upload settings:

UPLOAD_ALLOWED_FORMATS=jpg,png,pdf                # Supported file formats for upload
UPLOAD_MAX_FILE_SIZE=5242880                      # Max file size in bytes (5MB default)
UPLOAD_STORAGE=local                              # Storage type, 'local' or 's3'
UPLOAD_STORAGE_PATH="src/modules/upload/uploadedFiles/" # Path for storing files

# Image Processing Options
IMG_RESIZE_WIDTH=800                              # Default resize width
IMG_RESIZE_HEIGHT=600                             # Default resize height
IMG_FORMAT=jpeg                                   # Output format for images
IMG_QUALITY=80                                    # Image quality percentage
# IMG_WATERMARK_PATH="src/modules/upload/watermark/watermark.png" # Optional watermark path

Available Upload Routes (Example)

The Upload module includes predefined routes for handling file uploads, with configurable file validation and image processing options. These routes demonstrate the functionality and can be modified or extended as needed.

POST /upload/file

Description: Uploads a file with optional image processing (resizing, watermarking) if the file is an image.

Payload Example:

{
    "file": "<file data>" // File data sent as form-data with the key 'file'
}

Response:

{
    "filePath": "path/to/saved/file.jpg"
}

GET /upload/test

Description: Simple route to test if the Upload module is running. Returns a confirmation message if the route is functional.

Testing Upload Integration in Unity with C#

You can easily test the Upload module by making HTTP requests from any client, including Unity. Below is an example of how to call the Upload endpoint from Unity using UnityWebRequest.

Example Client Integration (using C# with UnityWebRequest)

using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using TMPro;

public class FileUploader : MonoBehaviour
{
    public TMP_Text statusText; // TextMeshPro text for displaying upload status
    private string apiUrl = "http://your-backend-url.com/upload/file";

    public void UploadFile(string filePath)
    {
        StartCoroutine(UploadCoroutine(filePath));
    }

    private IEnumerator UploadCoroutine(string path)
    {
        if (!File.Exists(path))
        {
            statusText.text = "File not found!";
            yield break;
        }

        byte[] fileData = File.ReadAllBytes(path);
        string fileName = Path.GetFileName(path);

        WWWForm form = new WWWForm();
        form.AddBinaryData("file", fileData, fileName);

        UnityWebRequest request = UnityWebRequest.Post(apiUrl, form);
        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            statusText.text = "Upload successful!";
        }
        else
        {
            statusText.text = "Upload failed: " + request.error;
        }
    }
}

Extending the Upload Module

The Upload module is designed to be modular and extensible to meet the unique requirements of your project. It currently includes the following components:

  • UploadService: Handles the core logic for uploading files, validating file types and sizes, and processing images (resizing, format conversion, watermarking) if applicable.

  • ImageProcessorService: Provides image manipulation functionality, allowing resizing, format conversion, and optional watermarking for image files.

  • UploadConfig: Centralized configuration service for managing settings such as allowed file formats, max file size, image processing options, and storage paths. These can be customized using environment variables.

  • UploadController: Exposes the main upload endpoint /upload/file for client requests to upload files and applies necessary validation.

With these components, the module can be customized and expanded to suit your specific project requirements, such as adding support for different storage backends (e.g., AWS S3) or integrating image optimization.

PreviousMailer

Last updated 7 months ago

🎗️