Skip to main content

Backend: @blocklet/uploader-server

The @blocklet/uploader-server package provides a suite of Express.js middleware designed to handle various file handling tasks on the backend of your blocklet. It serves as the server-side counterpart to the @blocklet/uploader frontend component, enabling features like direct file uploads, integration with remote sources, and resource serving.

While designed to work seamlessly with its frontend partner, it can also be used as a standalone solution for customized file upload logic. The package exports several modular middleware initializers that you can easily integrate into your Express application.

Core Middleware Interaction

The following diagram illustrates how the primary middleware components interact with the frontend and external services during an upload process.

Installation

To get started, add the package to your blocklet's dependencies.

Installation

bash
pnpm add @blocklet/uploader-server

General Usage

Here is a typical example of how to integrate the upload and companion middleware into your Express application's router. You can initialize the required middleware and then mount their handlers onto specific routes.

Express Router Example

javascript
import { initLocalStorageServer, initCompanion } from '@blocklet/uploader-server';
import express from 'express';

// Assume `env`, `user`, `auth`, `ensureComponentDid`, and `Upload` model are defined elsewhere
const router = express.Router();

// 1. Initialize the local storage server for direct uploads
const localStorageServer = initLocalStorageServer({
  path: env.uploadDir, // Directory to save uploads
  express,
  // Optional: Callback executed after a file is successfully uploaded
  onUploadFinish: async (req, res, uploadMetadata) => {
    const {
      id: filename,
      size,
      metadata: { filename: originalname, filetype: mimetype },
    } = uploadMetadata;

    // Construct the public URL for the uploaded file
    const obj = new URL(env.appUrl);
    obj.protocol = req.get('x-forwarded-proto') || req.protocol;
    obj.pathname = `/uploads/${filename}`;

    // Save file metadata to the database
    const doc = await Upload.insert({
      mimetype,
      originalname,
      filename,
      size,
      // ... other metadata from the request
    });

    // Return a JSON response to the frontend
    const resData = { url: obj.href, ...doc };
    return resData;
  },
});

// Mount the upload handler on a specific route
router.use('/uploads', user, auth, ensureComponentDid, localStorageServer.handle);

// 2. Initialize Companion for remote sources (e.g., URL, Unsplash)
const companion = initCompanion({
  path: env.uploadDir,
  express,
  providerOptions: env.providerOptions, // Your provider keys (e.g., Unsplash)
  uploadUrls: [env.appUrl], // The URL of your app
});

// Mount the companion handler on its route
router.use('/companion', user, auth, ensureComponentDid, companion.handle);

Available Middleware

The package exports several middleware initializers for different functionalities. Click on a card to view its detailed API reference and configuration options.

Next Steps

The @blocklet/uploader-server package provides the essential server-side building blocks for a robust file handling system in your blocklet. By combining these middleware functions, you can create a feature-rich upload experience for your users.

To get started, we recommend exploring the initLocalStorageServer documentation to set up the core direct upload functionality.