docs
0
# Video Uploads
1
2
Direct upload functionality for secure file transfers to Mux, providing pre-signed URLs and upload tracking with automatic asset creation upon completion.
3
4
## Capabilities
5
6
### Direct Upload Creation
7
8
Create secure, time-limited upload URLs for direct client-side file uploads to Mux.
9
10
```typescript { .api }
11
/**
12
* Create a direct upload URL
13
* @param body - Upload creation parameters
14
* @returns Promise resolving to the created upload configuration
15
*/
16
create(body: UploadCreateParams): Promise<Upload>;
17
18
interface UploadCreateParams {
19
/** CORS origin for browser uploads */
20
cors_origin?: string;
21
/** Asset settings for the created asset */
22
new_asset_settings?: NewAssetSettings;
23
/** Test mode flag */
24
test?: boolean;
25
/** Upload timeout in seconds */
26
timeout?: number;
27
}
28
29
interface Upload {
30
/** Unique identifier for the Direct Upload */
31
id: string;
32
/** CORS origin for browser uploads (required) */
33
cors_origin: string;
34
/** Current upload status */
35
status: 'waiting' | 'asset_created' | 'errored' | 'cancelled' | 'timed_out';
36
/** Max time in seconds for the signed upload URL to be valid */
37
timeout: number;
38
/** Pre-signed URL for uploading the file */
39
url: string;
40
/** Asset ID created from successful upload (only set once upload is in 'asset_created' state) */
41
asset_id?: string;
42
/** Error information if upload failed (only set if error occurred during asset creation) */
43
error?: UploadError;
44
/** Asset settings to apply when creating the asset */
45
new_asset_settings?: NewAssetSettings;
46
/** Indicates if this is a test Direct Upload (created asset will be a test asset) */
47
test?: boolean;
48
}
49
50
interface NewAssetSettings {
51
/** Playback policies for the created asset */
52
playback_policies?: Array<PlaybackPolicy>;
53
/** MP4 support settings */
54
mp4_support?: Mp4Support;
55
/** Audio normalization */
56
normalize_audio?: boolean;
57
/** Master file access */
58
master_access?: MasterAccess;
59
/** Input settings */
60
inputs?: Array<InputSettings>;
61
}
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
// Basic upload creation
68
const upload = await mux.video.uploads.create({
69
cors_origin: "https://myapp.example.com",
70
new_asset_settings: {
71
playback_policies: ["public"],
72
},
73
});
74
75
// Upload with advanced asset settings
76
const upload = await mux.video.uploads.create({
77
cors_origin: "https://myapp.example.com",
78
timeout: 3600, // 1 hour timeout
79
new_asset_settings: {
80
playback_policies: ["signed"],
81
mp4_support: "standard",
82
normalize_audio: true,
83
input: [
84
{
85
generated_subtitles: [
86
{
87
language_code: "en",
88
name: "English Auto-Generated",
89
},
90
],
91
},
92
],
93
},
94
});
95
96
// Client-side upload (example)
97
const formData = new FormData();
98
formData.append("file", videoFile);
99
100
const response = await fetch(upload.url, {
101
method: "PUT",
102
body: videoFile,
103
headers: {
104
"Content-Type": videoFile.type,
105
},
106
});
107
```
108
109
### Upload Management
110
111
Monitor and manage upload status and lifecycle.
112
113
```typescript { .api }
114
/**
115
* Retrieve upload details and status
116
* @param uploadId - The upload identifier
117
* @returns Promise resolving to upload details
118
*/
119
retrieve(uploadId: string): Promise<Upload>;
120
121
/**
122
* List uploads with optional filtering and pagination
123
* @param query - Listing parameters
124
* @returns Paginated list of uploads
125
*/
126
list(query?: UploadListParams): PagePromise<UploadsBasePage, Upload>;
127
128
interface UploadListParams extends BasePageParams {
129
/** Filter by upload status */
130
status?: 'waiting' | 'asset_created' | 'errored' | 'cancelled' | 'timed_out';
131
}
132
133
/**
134
* Cancel a pending upload
135
* @param uploadId - The upload identifier
136
* @returns Promise that resolves when cancellation is complete
137
*/
138
cancel(uploadId: string): Promise<void>;
139
```
140
141
### Upload Status Monitoring
142
143
Track upload progress and handle completion or failure states.
144
145
**Upload Lifecycle:**
146
147
1. **waiting** - Upload URL created, waiting for file upload
148
2. **asset_created** - File uploaded successfully, asset created
149
3. **errored** - Upload failed with error details
150
4. **cancelled** - Upload cancelled before completion
151
5. **timed_out** - Upload URL expired before file was uploaded
152
153
**Status Monitoring Example:**
154
155
```typescript
156
// Poll upload status
157
async function waitForUpload(uploadId: string): Promise<string> {
158
while (true) {
159
const upload = await mux.video.uploads.retrieve(uploadId);
160
161
switch (upload.status) {
162
case 'asset_created':
163
return upload.asset_id!;
164
165
case 'errored':
166
throw new Error(`Upload failed: ${upload.error?.message}`);
167
168
case 'cancelled':
169
throw new Error('Upload was cancelled');
170
171
case 'timed_out':
172
throw new Error('Upload timed out');
173
174
case 'waiting':
175
// Continue polling
176
await new Promise(resolve => setTimeout(resolve, 1000));
177
break;
178
}
179
}
180
}
181
182
// Usage
183
const upload = await mux.video.uploads.create({
184
cors_origin: "https://myapp.example.com",
185
});
186
187
// ... perform client-side upload to upload.url ...
188
189
const assetId = await waitForUpload(upload.id);
190
console.log(`Asset created: ${assetId}`);
191
```
192
193
## Error Handling
194
195
```typescript { .api }
196
interface UploadError {
197
/** Human-readable error message */
198
message?: string;
199
/** Label for the specific error */
200
type?: string;
201
}
202
```
203
204
**Common Upload Errors:**
205
206
- **timeout** - Upload URL expired before file was uploaded
207
- **invalid_file** - Uploaded file format not supported
208
- **file_too_large** - File exceeds maximum size limits
209
- **network_error** - Network failure during upload
210
- **processing_error** - Error processing uploaded file
211
212
## Client-Side Upload Implementation
213
214
### Browser Upload Example
215
216
```typescript
217
async function uploadVideoFile(
218
file: File,
219
uploadUrl: string,
220
onProgress?: (percent: number) => void
221
): Promise<void> {
222
return new Promise((resolve, reject) => {
223
const xhr = new XMLHttpRequest();
224
225
// Track upload progress
226
xhr.upload.addEventListener('progress', (event) => {
227
if (event.lengthComputable && onProgress) {
228
const percent = (event.loaded / event.total) * 100;
229
onProgress(percent);
230
}
231
});
232
233
xhr.addEventListener('load', () => {
234
if (xhr.status >= 200 && xhr.status < 300) {
235
resolve();
236
} else {
237
reject(new Error(`Upload failed with status ${xhr.status}`));
238
}
239
});
240
241
xhr.addEventListener('error', () => {
242
reject(new Error('Upload failed'));
243
});
244
245
xhr.open('PUT', uploadUrl);
246
xhr.setRequestHeader('Content-Type', file.type);
247
xhr.send(file);
248
});
249
}
250
251
// Usage
252
const upload = await mux.video.uploads.create({
253
cors_origin: window.location.origin,
254
});
255
256
await uploadVideoFile(
257
videoFile,
258
upload.url,
259
(percent) => console.log(`Upload ${percent.toFixed(1)}% complete`)
260
);
261
262
const assetId = await waitForUpload(upload.id);
263
```
264
265
### Node.js Upload Example
266
267
```typescript
268
import { createReadStream } from 'fs';
269
import fetch from 'node-fetch';
270
271
async function uploadVideoFileNode(
272
filePath: string,
273
uploadUrl: string
274
): Promise<void> {
275
const fileStream = createReadStream(filePath);
276
277
const response = await fetch(uploadUrl, {
278
method: 'PUT',
279
body: fileStream,
280
headers: {
281
'Content-Type': 'video/mp4', // Set appropriate MIME type
282
},
283
});
284
285
if (!response.ok) {
286
throw new Error(`Upload failed with status ${response.status}`);
287
}
288
}
289
```
290
291
## Types
292
293
```typescript { .api }
294
type PlaybackPolicy = 'public' | 'signed' | 'drm';
295
type Mp4Support = 'none' | 'standard' | 'capped-1080p';
296
type MasterAccess = 'temporary' | 'none';
297
298
interface InputSettings {
299
url?: string;
300
overlay_settings?: OverlaySettings;
301
generated_subtitles?: Array<GeneratedSubtitleSettings>;
302
start_time?: number;
303
end_time?: number;
304
type?: string;
305
}
306
307
interface GeneratedSubtitleSettings {
308
language_code?: string;
309
name?: string;
310
passthrough?: string;
311
}
312
313
interface OverlaySettings {
314
vertical_align?: 'top' | 'middle' | 'bottom';
315
vertical_margin?: string;
316
horizontal_align?: 'left' | 'center' | 'right';
317
horizontal_margin?: string;
318
width?: string;
319
height?: string;
320
opacity?: string;
321
}
322
```