Documents
FilesManager API Reference
FilesManager API Reference
Type
Document
Status
Published
Created
Feb 4, 2026
Updated
Feb 4, 2026
Updated by
Dosu Bot

FilesManager API Reference#

The FilesManager class provides programmatic access to the Strapi Media Library, enabling applications to manage media files through the Strapi client. It offers a complete set of CRUD operations for files uploaded through the Media Library, including finding, retrieving, updating, deleting, and uploading files.

The FilesManager integrates seamlessly with the Strapi client and uses the upload plugin API (/upload prefix) to interact with media files. Unlike the standard content API, the upload plugin returns flat arrays rather than the typical { data, meta } structure.

Getting Started#

Installation#

Install the @strapi/client package:

npm install @strapi/client

Client Initialization#

To use the FilesManager, initialize the Strapi client with your Strapi server's base URL and authentication credentials:

import { strapi } from '@strapi/client';

const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token',
});

The FilesManager is automatically instantiated when you create a client and is accessible via the client.files property. It shares the same HttpClient instance as the main client, ensuring consistent authentication through HTTP interceptors. Any custom headers configured on the client automatically apply to all file operations.

Basic Usage#

Access file management operations through the files property:

// Retrieve all files
const files = await client.files.find();

// Upload a new file
const uploadedFile = await client.files.upload(fileBlob);

// Update file metadata
const updated = await client.files.update(fileId, { 
  alternativeText: 'Description' 
});

API Methods#

The FilesManager provides five main methods for managing media files:

find()#

Retrieves a list of files from the Media Library based on optional query parameters.

Signature

find(queryParams?: FileQueryParams): Promise<FileListResponse>

Parameters

  • queryParams (optional): FileQueryParams object with:
    • filters: Record<string, any> - Query filters using Strapi filter operators (e.g., { name: { $contains: 'example' } })
    • sort: string | string[] - Sorting criteria (e.g., 'name:asc' or ['name:asc', 'createdAt:desc'])

Returns

Throws

  • FileForbiddenError if the user lacks permission to list files
  • HTTPError for connection issues or authentication failures

Example

// Find all files
const allFiles = await client.files.find();

// Find image files with specific name pattern, sorted by name
const imageFiles = await client.files.find({
  filters: {
    mime: { $contains: 'image' },
    name: { $contains: 'avatar' },
  },
  sort: ['name:asc'],
});

console.log(imageFiles); // Array of FileResponse objects

findOne()#

Retrieves a single file by its numeric ID.

Signature

findOne(fileId: number): Promise<FileResponse>

Parameters

  • fileId: number - The numeric identifier of the file

Returns

Throws

  • FileNotFoundError if the file doesn't exist
  • HTTPError for connection issues or authentication failures

Example

const file = await client.files.findOne(1);

console.log(file.name); // "example-image.png"
console.log(file.url); // "/uploads/example-image.png"
console.log(file.mime); // "image/png"
console.log(file.width); // 1920
console.log(file.height); // 1080

update()#

Updates metadata for an existing file. Note that this method only updates file metadata (name, alternativeText, caption), not the file content itself.

Signature

update(fileId: number, fileInfo: FileUpdateData): Promise<FileResponse>

Parameters

  • fileId: number - The file identifier
  • fileInfo: FileUpdateData object with updatable fields:
    • name: string (optional) - The file name
    • alternativeText: string (optional) - Alternative text for accessibility
    • caption: string (optional) - Caption or description

Returns

Throws

  • FileNotFoundError if the file doesn't exist
  • HTTPError for connection issues or authentication failures

Implementation Note

The update method uses FormData with a POST request (not PUT/PATCH) as required by the Strapi upload plugin API. The fileInfo is JSON stringified when added to FormData.

Example

const updatedFile = await client.files.update(1, {
  name: 'product-hero-image.png',
  alternativeText: 'Hero image showing our flagship product',
  caption: 'Featured on homepage banner',
});

console.log(updatedFile.name); // "product-hero-image.png"
console.log(updatedFile.alternativeText); // "Hero image showing..."

delete()#

Deletes a file from the Media Library by its ID.

Signature

delete(fileId: number): Promise<FileResponse>

Parameters

  • fileId: number - The file identifier

Returns

Throws

  • FileNotFoundError if the file doesn't exist
  • FileForbiddenError if the user lacks delete permissions
  • HTTPError for connection issues or authentication failures

Example

const deletedFile = await client.files.delete(1);

console.log('File deleted successfully');
console.log('Deleted file ID:', deletedFile.id);
console.log('Deleted file name:', deletedFile.name);

upload()#

Uploads a new media file to the Strapi Media Library. Supports both browser (Blob/File) and Node.js (Buffer) environments.

Signature

upload(file: Blob, options?: BlobUploadOptions): Promise<MediaUploadResponse>
upload(file: Buffer, options: BufferUploadOptions): Promise<MediaUploadResponse>

Parameters

Returns

Throws

  • FileForbiddenError if the user lacks upload permissions
  • Error if Buffer is uploaded without filename/mimetype
  • HTTPError for connection issues or authentication failures

Implementation Notes

Examples

// Browser: Upload from file input
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const result = await client.files.upload(file, {
  fileInfo: { 
    alternativeText: 'User uploaded avatar',
    caption: 'Profile picture'
  }
});

// Browser: Upload from Blob
const blob = await fetch('/path/to/image.png').then(r => r.blob());
const result = await client.files.upload(blob, {
  fileInfo: { alternativeText: 'Downloaded image' }
});

// Node.js: Upload from Buffer
import fs from 'fs';
const buffer = fs.readFileSync('./image.png');
const result = await client.files.upload(buffer, {
  filename: 'uploaded-image.png',
  mimetype: 'image/png',
  fileInfo: { 
    alternativeText: 'Server-side uploaded image',
    caption: 'Generated thumbnail'
  }
});

console.log(result[0].id); // ID of uploaded file
console.log(result[0].url); // URL to access the file

TypeScript Types#

The FilesManager uses strongly typed interfaces for all operations. All types are exported from the package for use in your TypeScript applications.

FileQueryParams#

Query parameters for finding files:

interface FileQueryParams {
  filters?: Record<string, any>; // Strapi filter operators
  sort?: string | string[]; // Sorting criteria
}

The filters parameter accepts Strapi's standard filter operators ($contains, $eq, $ne, etc.). Note that the upload plugin doesn't support standard pagination parameters like pagination[page] or pagination[pageSize].

FileResponse#

Complete file metadata structure returned by all operations:

interface FileResponse {
  id: number; // Numeric file ID
  documentId: string; // Document identifier
  name: string; // File name
  alternativeText?: string; // Alt text for accessibility
  caption?: string; // File caption/description
  width: number; // Image width in pixels
  height: number; // Image height in pixels
  hash: string; // File hash
  ext: string; // File extension (e.g., ".png")
  mime: string; // MIME type (e.g., "image/png")
  url: string; // Public URL to access the file
  size: number; // File size in kilobytes
  provider: string; // Storage provider (e.g., "local")
  previewUrl: string | null; // Preview URL if available
  provider_metadata?: any; // Provider-specific metadata
  createdAt: string; // ISO 8601 creation timestamp
  updatedAt: string; // ISO 8601 update timestamp
  formats?: any; // Available image formats/sizes
  folderPath?: string; // Folder path in Media Library
}

FileListResponse#

Response type for file listing operations:

type FileListResponse = Array<FileResponse>;

Unlike the standard Strapi content API, the upload plugin returns a flat array without the { data: [], meta: {} } wrapper structure.

FileUpdateData#

Fields that can be updated on existing files:

interface FileUpdateData {
  name?: string; // Update file name
  alternativeText?: string; // Update alt text
  caption?: string; // Update caption
}

All fields are optional. Only the provided fields will be updated.

BlobUploadOptions#

Options for Blob/File uploads (browser environments):

interface BlobUploadOptions {
  fileInfo?: FileUpdateData; // Optional metadata for uploaded file
}

When uploading Blobs or Files, the filename and MIME type are automatically inferred from the Blob object.

BufferUploadOptions#

Options for Buffer uploads (Node.js environments):

interface BufferUploadOptions {
  filename: string; // Required: Name for the uploaded file
  mimetype: string; // Required: MIME type (e.g., "image/png")
  fileInfo?: FileUpdateData; // Optional metadata for uploaded file
}

When uploading Buffers, you must explicitly provide the filename and mimetype parameters.

MediaUploadResponse#

Response from upload operations:

type MediaUploadResponse = Array<FileResponse>;

Returns an array of uploaded files (typically contains one element for single file uploads).

Error Handling#

The FilesManager implements robust error handling with specialized error classes that provide context-specific information about failures.

Error Types#

FileNotFoundError

Thrown when a file with the specified ID doesn't exist. This error typically occurs during findOne(), update(), or delete() operations and includes the fileId in the error details for debugging.

FileForbiddenError

Thrown when the authenticated user lacks permissions for the requested file operation. This can occur during find(), upload(), or delete() operations. The error may include a fileId when applicable.

HTTPError

Generic HTTP errors thrown for connection issues, server unreachability, or authentication failures. All FilesManager methods can throw this error type.

Error Transformation Architecture#

The FilesManager uses an interceptor-based architecture to transform generic HTTP errors into domain-specific file errors:

  1. FileErrorMapper creates error interceptors that map HTTP status codes to specific error types
  2. Each method creates an HTTP client with file-specific error handling
  3. Response interceptors automatically transform errors before they reach your application code

Error Handling Example#

import { FileNotFoundError, FileForbiddenError } from '@strapi/client';

try {
  const file = await client.files.findOne(999);
} catch (error) {
  if (error instanceof FileNotFoundError) {
    console.error('File not found:', error.message);
    // Handle missing file (show 404 page, use placeholder, etc.)
  } else if (error instanceof FileForbiddenError) {
    console.error('Permission denied:', error.message);
    // Handle permission error (show auth prompt, redirect, etc.)
  } else {
    console.error('Unexpected error:', error);
    // Handle other errors (network issues, server errors, etc.)
  }
}

Best Practices#

  • Always wrap FilesManager operations in try-catch blocks
  • Check for specific error types using instanceof for precise error handling
  • Include the file ID in error logs to aid debugging
  • Provide user-friendly error messages in your UI
  • Consider retry logic for network-related HTTPErrors

Key Characteristics#

API Differences from Content API#

The FilesManager uses the Strapi upload plugin API, which differs from the standard content API in several ways:

Cross-Environment Support#

The FilesManager is designed to work seamlessly in both browser and Node.js environments:

Additional Resources#

For more information about the FilesManager and media file management in Strapi: