MediaService
@blobs/sdk / services / MediaService
Defined in: services/MediaService.ts:121
Handles file upload, download URL generation, and lifecycle management for media records.
Implements a two-phase upload (server prepares a signed URL, then client PUTs the body),
automatically falling back to chunked uploads for large files. Delegates raw byte transfer
to whichever storage provider is configured for the user (resolved server-side via
StorageService).
Example
const sdk = createSDK({ networks: [...] });const file = document.querySelector<HTMLInputElement>('#file')!.files![0];const res = await sdk.media.upload({ file });if (res.success) console.log(res.data!.id);Constructors
Constructor
new MediaService(
context):MediaService
Defined in: services/MediaService.ts:129
Constructs a MediaService bound to the given context.
Parameters
context
Shared BlobsContext providing transport, cache, config, and event manager.
Returns
MediaService
Properties
MediaUrlOptions
readonlystaticMediaUrlOptions:object
Defined in: services/MediaService.ts:488
Default option values used by getMediaUrl — exposed as a static for callers that want to reference the canonical defaults (e.g. UI components).
includeToken
includeToken:
boolean=false
Include the auth token as a URL query parameter (for private media in <img> tags).
inline
inline:
boolean=false
Use the view endpoint (inline disposition) instead of download (attachment).
Methods
upload()
Defined in: services/MediaService.ts:197
Uploads a media file using the two-phase protocol — preparing the upload server-side, then sending the bytes to the returned signed URL. Automatically dispatches to chunked upload when the prepare response indicates chunking is required.
Parameters
input
UploadMediaInput with file body and optional blob_id/filename.
options?
Optional network/tenant scoping options.
Returns
A Response containing the persisted Media record on success.
Throws
ApiError when prepare or upload phases fail.
Example
const res = await sdk.media.upload({ file, blob_id: 'blob_123' });getById()
Defined in: services/MediaService.ts:381
Fetches a media record by ID, served from cache when available.
Parameters
id
string
The media identifier.
useCache?
boolean = true
When true (default), returns a cached value if present; pass false to force a network fetch.
options?
Optional network/tenant scoping options.
Returns
A Response containing the Media record.
Throws
NotFoundError when no media with the given ID exists.
Throws
PermissionError when the user lacks read access.
list()
Defined in: services/MediaService.ts:409
Lists media records, optionally scoped to a single blob.
Parameters
params?
Optional filter; provide blob_id to list media attached to a specific blob.
blob_id?
string
options?
Optional network/tenant scoping options.
Returns
A Response containing matching Media records.
delete()
delete(
id,options?):Promise<Response<void>>
Defined in: services/MediaService.ts:430
Deletes a media record and clears its cache entry.
Parameters
id
string
The media identifier.
options?
Optional network/tenant scoping options.
Returns
Promise<Response<void>>
A Response with no payload on success.
Throws
NotFoundError when no media with the given ID exists.
Throws
PermissionError when the user lacks delete access.
bulkDelete()
bulkDelete(
mediaIds,options?):Promise<Response<{results:BulkDeleteMediaResult[]; }>>
Defined in: services/MediaService.ts:454
Deletes multiple media records in one round-trip and clears cache entries for each successful deletion.
Parameters
mediaIds
string[]
Array of media IDs to delete (max 100 per request).
options?
Optional network/tenant scoping options.
Returns
Promise<Response<{ results: BulkDeleteMediaResult[]; }>>
A Response containing { results } — a BulkDeleteMediaResult entry per requested ID.
Throws
ValidationError when more than 100 IDs are provided.
getMediaUrl()
getMediaUrl(
mediaId,options?):string
Defined in: services/MediaService.ts:507
Builds a URL pointing to a media file’s view or download endpoint, optionally
including the access token as a query parameter for use in contexts (e.g. <img> tags)
that cannot send Authorization headers.
Parameters
mediaId
string
The media identifier.
options?
URL generation options.
includeToken?
boolean
When true, appends ?token=... so unauthenticated <img> tags can load private media.
inline?
boolean
When true, uses the view endpoint (inline disposition) instead of download (attachment).
network?
string
Specific network name to resolve host/prefix from.
Returns
string
The fully-qualified media URL, or a relative fallback if no network is configured.
getDownloadUrl()
getDownloadUrl(
mediaId,network?):string
Defined in: services/MediaService.ts:557
Returns the download (attachment disposition) URL for a media file.
Parameters
mediaId
string
The media identifier.
network?
string
Optional specific network name to resolve host/prefix from.
Returns
string
The fully-qualified download URL.
Deprecated
Use getMediaUrl instead for clearer option handling.
getViewUrl()
getViewUrl(
mediaId,options?):string
Defined in: services/MediaService.ts:568
Returns the view (inline disposition) URL for a media file.
Parameters
mediaId
string
The media identifier.
options?
URL options including optional includeToken and network.
includeToken?
boolean
network?
string
Returns
string
The fully-qualified view URL.
getThumbnailUrl()
getThumbnailUrl(
media,options?):string
Defined in: services/MediaService.ts:580
Returns a thumbnail URL for a media record, falling back to the view URL when
the record has no thumbnail_url. Useful for image grids and previews.
Parameters
media
The Media record to render.
options?
URL options including optional includeToken and network.
includeToken?
boolean
network?
string
Returns
string
A URL suitable for thumbnail rendering.
fetchAsObjectUrl()
fetchAsObjectUrl(
mediaId,options?):Promise<{url:string;revoke: () =>void; } |null>
Defined in: services/MediaService.ts:601
Fetches a media file via authenticated request and wraps the response as an object URL,
suitable for displaying private media in <img> tags without exposing tokens in the URL.
Remember to call the returned revoke() function when the URL is no longer needed.
Parameters
mediaId
string
The media identifier.
options?
Optional network selector.
network?
string
Returns
Promise<{ url: string; revoke: () => void; } | null>
An object containing the url (object URL) and a revoke() cleanup function, or null on failure.
uploadWithProgress()
uploadWithProgress(
file,options?):Promise<Response<Media>>
Defined in: services/MediaService.ts:645
Uploads a file via the two-phase protocol with byte-level progress tracking and cancellation support. Automatically falls back to chunked upload for large files.
Parameters
file
Blob | File
The file or blob to upload.
options?
Upload options including filename, blob_id, onProgress callback, and signal AbortSignal.
filename?
string
blob_id?
string
onProgress?
(progress) => void
signal?
AbortSignal
Returns
A Response containing the persisted Media record on success.
Throws
ApiError when prepare or upload phases fail; rejects when the abort signal fires.
Example
const ctrl = new AbortController();const res = await sdk.media.uploadWithProgress(file, { onProgress: ({ percentage }) => console.log(`${percentage}%`), signal: ctrl.signal,});subscribe()
subscribe(
event,callback,options?): () =>void
Defined in: services/MediaService.ts:889
Subscribes to a real-time media event by name. Delegates to the unified ctx.wireEvents
manager — see WireEventManager for ordering, buffering, and error-routing semantics.
Parameters
event
string
Wire event name (e.g. media.upload.completed).
callback
(data) => void
Handler invoked with the event payload.
options?
Optional network/tenant scoping options.
Returns
An unsubscribe function that removes this listener.
() => void
onUploadPrepared()
onUploadPrepared(
callback,options?): () =>void
Defined in: services/MediaService.ts:904
Subscribes to media.upload.prepared events fired when a media upload is reserved server-side.
Parameters
callback
PlatformEventCallback<MediaUploadPreparedEvent>
Handler receiving the typed MediaUploadPreparedEvent payload.
options?
Optional network/tenant scoping options.
Returns
An unsubscribe function.
() => void
onUploadCompleted()
onUploadCompleted(
callback,options?): () =>void
Defined in: services/MediaService.ts:918
Subscribes to media.upload.completed events fired once a media file has been fully uploaded.
Parameters
callback
PlatformEventCallback<MediaUploadCompletedEvent>
Handler receiving the typed MediaUploadCompletedEvent payload.
options?
Optional network/tenant scoping options.
Returns
An unsubscribe function.
() => void
onUploadFailed()
onUploadFailed(
callback,options?): () =>void
Defined in: services/MediaService.ts:932
Subscribes to media.upload.failed events fired when a media upload fails server-side.
Parameters
callback
PlatformEventCallback<MediaUploadFailedEvent>
Handler receiving the typed MediaUploadFailedEvent payload.
options?
Optional network/tenant scoping options.
Returns
An unsubscribe function.
() => void
onMediaDeleted()
onMediaDeleted(
callback,options?): () =>void
Defined in: services/MediaService.ts:946
Subscribes to media.deleted events fired when a media record is removed.
Parameters
callback
PlatformEventCallback<MediaDeletedEvent>
Handler receiving the typed MediaDeletedEvent payload.
options?
Optional network/tenant scoping options.
Returns
An unsubscribe function.
() => void