typescriptadvanced

Multipart Upload Stream Handler

Handles multipart file uploads with streaming to disk without buffering the entire file in memory.

typescript
import { createWriteStream } from 'fs';
import { pipeline } from 'stream/promises';
import { Request, Response } from 'express';
import { randomUUID } from 'crypto';
import path from 'path';

export async function handleUpload(req: Request, res: Response) {
  const boundary = req.headers['content-type']?.split('boundary=')[1];
  if (!boundary) {
    return res.status(400).json({ error: 'Missing boundary' });
  }

  const filename = `${randomUUID()}${path.extname(req.headers['x-filename'] || '.bin')}`;
  const dest = path.join('/tmp/uploads', filename);

  try {
    await pipeline(req, createWriteStream(dest));
    res.json({ file: filename, path: dest });
  } catch (err) {
    res.status(500).json({ error: 'Upload failed' });
  }
}

Use Cases

  • Large file uploads
  • Cloud storage uploads

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.