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
- FileListResponse: Array of file objects
Throws
FileForbiddenErrorif the user lacks permission to list filesHTTPErrorfor 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
- FileResponse: Single file object with complete metadata
Throws
FileNotFoundErrorif the file doesn't existHTTPErrorfor 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 identifierfileInfo: FileUpdateData object with updatable fields:name: string (optional) - The file namealternativeText: string (optional) - Alternative text for accessibilitycaption: string (optional) - Caption or description
Returns
- FileResponse: Updated file object
Throws
FileNotFoundErrorif the file doesn't existHTTPErrorfor 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
- FileResponse: The deleted file object
Throws
FileNotFoundErrorif the file doesn't existFileForbiddenErrorif the user lacks delete permissionsHTTPErrorfor 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
file: Blob | Buffer - The file to upload- Blob/File for browser environments - filename and MIME type are inferred
- Buffer for Node.js environments - requires explicit filename and MIME type
options:- BlobUploadOptions:
{ fileInfo?: FileUpdateData }(optional for Blob/File) - BufferUploadOptions:
{ filename: string, mimetype: string, fileInfo?: FileUpdateData }(required for Buffer)
- BlobUploadOptions:
Returns
- MediaUploadResponse: Array of FileResponse objects (typically contains one item)
Throws
FileForbiddenErrorif the user lacks upload permissionsErrorif Buffer is uploaded without filename/mimetypeHTTPErrorfor connection issues or authentication failures
Implementation Notes
- Blob uploads automatically infer filename and MIME type from the Blob object
- Buffer uploads require explicit filename and mimetype parameters
- Buffer is converted to Blob internally for upload
- Uses FormData for multipart upload
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#
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.
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:
- FileErrorMapper creates error interceptors that map HTTP status codes to specific error types
- Each method creates an HTTP client with file-specific error handling
- 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
instanceoffor 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:
- API Prefix: Uses
/uploadprefix instead of the/apiprefix used by content types - Response Structure: Returns flat arrays (e.g.,
[{...}, {...}]) instead of the wrapped{ data: [...], meta: {...} }structure - Pagination: No standard pagination support - pagination parameters are not available for file queries
- Update Method: Uses POST with FormData instead of PUT or PATCH requests
Cross-Environment Support#
The FilesManager is designed to work seamlessly in both browser and Node.js environments:
- Supports Blob/File objects for browser uploads with automatic filename and MIME type detection
- Supports Buffer objects for Node.js uploads with required filename and MIME type parameters
- Automatic Buffer detection and conversion for Node.js environments
- Fallback handling for unknown file types
Additional Resources#
For more information about the FilesManager and media file management in Strapi:
- Strapi Client README with examples
- FilesManager unit tests - comprehensive test suite demonstrating all methods
- Integration tests - real-world usage patterns
- Type definitions source
- Error definitions source