Examples File transfer

Browser-to-browser file transfer

Stream a File over a named action channel with filename and MIME metadata, receive-side approval, progress callbacks on both ends, and mid-flight cancellation.

Approval, progress, and download

Register onReceive before onMessage so incoming offers are checked before chunks transfer. Trystero chunks the file, paces writes against RTCDataChannel.bufferedAmount, and delivers a reassembled Uint8Array to onMessage.

import {joinRoom} from 'trystero'

const room = joinRoom({appId: 'drop.example.com'}, dropId)
const files = room.makeAction('file')

// Inspect size and metadata before payload bytes are transmitted
files.onReceive(({byteLength, metadata, userId, signal}) => {
  if (byteLength > 100 * 1024 ** 2) return false
  return askToAcceptFile({from: userId, name: metadata.name, byteLength, signal})
})

files.onReceiveProgress((progress, {userId, metadata}) => {
  updateProgress(userId, metadata.id, progress)
})

files.onMessage((bytes, {userId, metadata}) => {
  const blob = new Blob([bytes], {type: metadata.type})
  const url = URL.createObjectURL(blob)
  showDownload({from: userId, url, name: metadata.name, size: blob.size})
})

fileInput.onchange = async () => {
  const file = fileInput.files?.[0]
  if (!file) return

  const controller = new AbortController()
  cancelButton.onclick = () => controller.abort()

  try {
    await files.send(file, {
      metadata: {id: crypto.randomUUID(), name: file.name, type: file.type},
      onProgress: (progress, {userId}) => showSendingProgress(userId, progress),
      signal: controller.signal
    })
  } catch (err) {
    // err.kind: 'rejected' | 'disconnected' | 'timeout' | 'aborted'
    if (err.kind !== 'aborted') showTransferError(err)
  }
}

askToAcceptFile() resolves to true or false and should dismiss its prompt if signal aborts. Declining rejects the sender's send() promise with err.kind === 'rejected'. Omitting target sends to everyone in the room; pass a userId to send to a single recipient.

Operational constraints

  • Rooms default to a 256 MiB concurrent receive budget. Increase maxReceiveBytes on receivers for larger transfers, keeping in mind payloads are reassembled in browser memory.
  • A resolved send() indicates local transmission finished; use a kind: 'request' action if you need explicit receipt confirmation.
  • Both peers must remain online for the duration of the transfer.
  • Sanitize sender-provided filenames before rendering, and call URL.revokeObjectURL() when download links are dismissed.