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
pnpm add @blocklet/uploader-serverGeneral 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
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({See all 26 lines
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.