or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

analytics-metrics.mdclient-setup.mddata.mddelivery-usage.mderror-handling.mdindex.mdjwt-signing.mdjwt.mdlive-streaming.mdplayback-control.mdsystem-operations.mdsystem.mdtranscription-vocabularies.mdupload-utilities.mdvideo-assets.mdvideo-playback.mdvideo-uploads.mdvideo.mdweb-inputs.mdwebhooks.md

upload-utilities.mddocs/

0

# Upload Utilities

1

2

File upload utilities and helper functions for handling various input types, multipart form encoding, and file object creation across different JavaScript environments.

3

4

## Capabilities

5

6

### File Object Creation

7

8

Convert various input types to File objects compatible with Mux upload APIs.

9

10

```typescript { .api }

11

/**

12

* Convert various inputs to File objects for uploads

13

* @param value - Input data to convert to File

14

* @param name - Optional filename

15

* @param options - Optional file properties

16

* @returns Promise that resolves to File object ready for upload

17

*/

18

function toFile(

19

value: ToFileInput | PromiseLike<ToFileInput>,

20

name?: string | null | undefined,

21

options?: FilePropertyBag | undefined

22

): Promise<FileLike>;

23

24

type Uploadable = FileLike | ResponseLike | FsReadStream;

25

type ToFileInput = Uploadable | Exclude<BlobLikePart, string> | AsyncIterable<BlobLikePart>;

26

type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView;

27

28

interface FilePropertyBag {

29

/** MIME type of the file */

30

type?: string;

31

/** Last modified timestamp */

32

lastModified?: number;

33

}

34

```

35

36

**Usage Examples:**

37

38

```typescript

39

import { toFile } from '@mux/mux-node';

40

import { createReadStream } from 'fs';

41

42

// Convert Buffer to File

43

const buffer = Buffer.from('video data');

44

const file1 = await toFile(buffer, 'video.mp4', { type: 'video/mp4' });

45

46

// Convert ReadStream to File

47

const stream = createReadStream('./video.mp4');

48

const file2 = await toFile(stream, 'video.mp4');

49

50

// Convert fetch Response to File

51

const response = await fetch('https://example.com/video.mp4');

52

const file3 = await toFile(response, 'downloaded-video.mp4');

53

54

// Convert existing File-like object

55

const existingFile = document.getElementById('fileInput').files[0]; // Browser

56

const file4 = await toFile(existingFile);

57

```

58

59

### File System Integration

60

61

Create File objects directly from file system paths (Node.js environments).

62

63

```typescript { .api }

64

/**

65

* Create File object from file system path

66

* @param path - Absolute or relative path to file

67

* @returns File object created from file system

68

*/

69

function fileFromPath(path: string): File;

70

```

71

72

**Usage Examples:**

73

74

```typescript

75

import { fileFromPath } from '@mux/mux-node';

76

77

// Create File from file system path

78

const file = fileFromPath('./videos/sample.mp4');

79

80

// Use with upload creation

81

const upload = await mux.video.uploads.create({

82

new_asset_settings: {

83

playback_policies: ['public'],

84

},

85

});

86

87

// Upload the file (this is conceptual - actual upload happens client-side)

88

// The fileFromPath result would be used in multipart form construction

89

```

90

91

92

93

## Type Definitions

94

95

### Input Types

96

97

```typescript { .api }

98

interface FileLike extends BlobLike {

99

/** Last modified timestamp */

100

readonly lastModified: number;

101

/** Filename */

102

readonly name: string;

103

}

104

105

interface BlobLike {

106

/** Blob size in bytes */

107

readonly size: number;

108

/** MIME type */

109

readonly type: string;

110

/** Read as text */

111

text(): Promise<string>;

112

/** Slice the blob */

113

slice(start?: number, end?: number): BlobLike;

114

}

115

116

interface ResponseLike {

117

/** Response URL */

118

url: string;

119

/** Convert to blob */

120

blob(): Promise<BlobLike>;

121

}

122

123

interface FsReadStream {

124

/** File path */

125

path: string;

126

/** Read stream */

127

pipe<T extends NodeJS.WritableStream>(destination: T): T;

128

/** Add event listener */

129

on(event: string, listener: (...args: any[]) => void): this;

130

/** Remove event listener */

131

off(event: string, listener: (...args: any[]) => void): this;

132

}

133

```

134

135

### Utility Types

136

137

```typescript { .api }

138

interface HeadersLike {

139

/** Get header value */

140

get(name: string): string | null;

141

/** Check if header exists */

142

has(name: string): boolean;

143

/** Iterate over headers */

144

[Symbol.iterator](): Iterator<[string, string]>;

145

}

146

147

interface FormDataEntryValue {

148

/** Form field name */

149

name: string;

150

/** Form field value */

151

value: string | File;

152

}

153

```

154

155

## Cross-Platform Compatibility

156

157

### Node.js Environment

158

159

```typescript

160

import { createReadStream } from 'fs';

161

import { toFile, fileFromPath } from '@mux/mux-node';

162

163

// File system integration

164

const fileFromDisk = fileFromPath('./video.mp4');

165

166

// Stream handling

167

const stream = createReadStream('./video.mp4');

168

const fileFromStream = await toFile(stream, 'video.mp4');

169

170

// Buffer handling

171

const buffer = Buffer.from(videoData);

172

const fileFromBuffer = await toFile(buffer, 'video.mp4', {

173

type: 'video/mp4',

174

lastModified: Date.now(),

175

});

176

```

177

178

### Browser Environment

179

180

```typescript

181

import { toFile } from '@mux/mux-node';

182

183

// File input handling

184

const input = document.querySelector('input[type="file"]') as HTMLInputElement;

185

const browserFile = input.files?.[0];

186

187

if (browserFile) {

188

const file = await toFile(browserFile);

189

// Use file for upload

190

}

191

192

// Fetch response handling

193

const response = await fetch('/api/video');

194

const fileFromResponse = await toFile(response, 'downloaded.mp4');

195

196

// Blob handling

197

const blob = new Blob([videoData], { type: 'video/mp4' });

198

const fileFromBlob = await toFile(blob, 'video.mp4');

199

```

200

201

### Universal Patterns

202

203

```typescript

204

async function createUploadableFile(

205

source: string | Buffer | Blob | File | Response,

206

filename: string

207

): Promise<File> {

208

if (typeof source === 'string') {

209

// Assume it's a file path in Node.js

210

return fileFromPath(source);

211

} else {

212

// Convert other types using toFile

213

return await toFile(source, filename);

214

}

215

}

216

217

// Usage across environments

218

const file1 = await createUploadableFile('./video.mp4', 'video.mp4'); // Node.js

219

const file2 = await createUploadableFile(browserFile, 'video.mp4'); // Browser

220

const file3 = await createUploadableFile(buffer, 'video.mp4'); // Universal

221

```

222

223

## Error Handling

224

225

```typescript

226

import { toFile } from '@mux/mux-node';

227

228

async function safeFileConversion(input: unknown, filename: string): Promise<File | null> {

229

try {

230

return await toFile(input, filename);

231

} catch (error) {

232

console.error('File conversion failed:', error);

233

return null;

234

}

235

}

236

237

// Usage with error handling

238

const file = await safeFileConversion(userInput, 'upload.mp4');

239

if (file) {

240

console.log('File ready for upload:', file.name);

241

} else {

242

console.error('Unable to create file for upload');

243

}

244

```