A Blob holds immutable binary data. A File adds a name and modification metadata, and commonly comes from a file input or drag-and-drop. This guide follows the main decisions: read the bytes, preview them through an object URL, or send them without converting to text.

Blob API

What is a Blob?

A Blob object represents immutable, raw binary data. Think of it as a container for file-like data that can be:

  • Read as text or binary
  • Converted to streams for processing
  • Used by APIs that accept Blob. APIs requiring a File name or other metadata may specifically need a File

Creating blobs

js
// From JSON data
const obj = { hello: 'world' }
const jsonBlob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json' })

/**
 *  Blob {
 *    size: 22, // in bytes
 *    type: 'application/json'
 *  }
 */

// From text
const textBlob = new Blob(['Hello, world!'], { type: 'text/plain' })
// From array buffer (binary data)
const buffer = new ArrayBuffer(8)
const binaryBlob = new Blob([buffer], { type: 'application/octet-stream' })

How to read blobs

FileReader API

You can read Blob data using the FileReader API:

js
const reader = new FileReader()
reader.onload = (e) => {
  console.log('Blob data as text:', e.target.result)
}
reader.readAsText(jsonBlob) // Read as text

Creating object URLs from blobs

URL.createObjectURL() generates a temporary URL that references the Blob data:

js
const blob = new Blob([JSON.stringify({ hello: 'world' })], {
  type: 'application/json',
})

// Create a URL: "blob:https://example.com/ff415f41-2b1b-4e47-bc1c-37112e0ff4b2"
const blobUrl = URL.createObjectURL(blob)

// Use the URL (e.g., for downloads)
const link = document.createElement('a')
link.href = blobUrl
link.download = 'data.json'
link.click()

// Clean up - important for memory management!
URL.revokeObjectURL(blobUrl)

Important: Always revoke object URLs when done to prevent memory leaks. The URL remains valid until the document is unloaded or you explicitly revoke it.

File API

Understanding File objects

A File object is a specialized Blob with additional metadata like filename and modification date. Files typically come from:

  • <input type="file"> elements
  • Drag-and-drop operations
  • Programmatic creation for testing or data generation

Creating files programmatically

js
const file = new File(
  ['hello', 'world'], // Array of content parts
  'test.txt', // Filename
  {
    type: 'text/plain',
    lastModified: Date.now(),
  }
)

/**
 * File {
 *   name: "test.txt",
 *   lastModified: 1594093337229,
 *   lastModifiedDate: Tue Jul 07 2020 11:42:17 GMT+0800 (China Standard Time),
 *   size: 10,
 *   type: "text/plain"
 * }
 */

FileReader API

FileReader reads file contents asynchronously and converts them to different formats:

js
// Choose one method for each read operation.
const reader = new FileReader()
reader.onload = () => console.log(reader.result)
reader.onerror = () => console.error(reader.error)
reader.readAsDataURL(file)

// Alternatives, using separate readers:
const textReader = new FileReader()
textReader.readAsText(file)
const bufferReader = new FileReader()
bufferReader.readAsArrayBuffer(file)

Do not start another read on the same reader while its readyState is LOADING; the File API requires an InvalidStateError in that case. For text or bytes, await file.text() and await file.arrayBuffer() are alternatives.

Preview uploaded images with object URLs

An object URL references the file without first encoding its contents into a base64 string:

Interactive playground
Edit TSX · updates automatically
Preview

Advantages of Object URLs:

  • Instant preview (no encoding needed)
  • Memory efficient
  • No base64 bloat
  • Avoids a large encoded string. Decoding and displaying the image still consumes resources

Preview uploaded images with base64

When you need the actual data (e.g., for upload, storage, or manipulation):

Interactive playground
Edit TSX · updates automatically
Preview

When to use readAsDataURL:

  • Need base64 for APIs that require it
  • Sending to a text-only storage interface. IndexedDB itself can store Blob objects
  • Sending images in JSON payloads
  • Image manipulation before upload

Downsides:

  • Slower than object URLs
  • Large base64 strings (33% larger than binary)
  • Higher memory usage

Historical example: a PDF.js worker with webpack

The following pattern applies to classic-script workers in historical PDF.js 2.x builds with webpack and raw-loader 4. It is not a recipe for current module-worker builds. For a current installation, follow the PDF.js package examples for your installed version and bundler. The underlying issue is a worker file path that is not emitted as a served asset. The traditional approach of pointing to a static file path breaks when using webpack or other bundlers:

The problem

js
import * as pdfjsLib from 'pdfjs-dist'

// ❌ This breaks after bundling - path becomes incorrect
pdfjsLib.GlobalWorkerOptions.workerSrc = './node_modules/pdfjs-dist/build/pdf.worker.js'

Issues:

  • Relative paths don't work in production bundles
  • Worker file might not be copied to dist folder
  • CDN hosting complicates paths further

The solution: Blob URLs

Convert the worker code to a Blob and create an object URL:

js
import * as pdfjsLib from 'pdfjs-dist'
// Use raw-loader to import worker code as a string
import pdfjsWorker from 'raw-loader!pdfjs-dist/build/pdf.worker.min.js'

// Create Blob from worker code
const pdfjsWorkerBlob = new Blob([pdfjsWorker], {
  type: 'application/javascript',
})

// Generate object URL
const pdfjsWorkerBlobURL = URL.createObjectURL(pdfjsWorkerBlob)

// Set worker source
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorkerBlobURL

Keep the Blob URL alive while the worker may need it. Revoke it after the worker is destroyed; revoking immediately can prevent the worker from loading. Your Content Security Policy must also allow the worker source you choose.

Best practices

1. Always clean up object URLs

An object URL should remain valid for the lifetime of its preview. Return a cleanup function so the caller can release it when the preview is replaced or removed:

js
function showBlobPreview(img, blob) {
  const url = URL.createObjectURL(blob)
  img.src = url
  return () => {
    if (img.src === url) img.removeAttribute('src')
    URL.revokeObjectURL(url)
  }
}

const disposePreview = showBlobPreview(img, blob)
// Call disposePreview() when replacing the preview or unmounting its component.

2. Validate file types

js
function handleFile(file) {
  const allowedTypes = ['image/png', 'image/jpeg', 'image/gif']

  if (!allowedTypes.includes(file.type)) {
    alert('Please upload PNG, JPEG, or GIF images only')
    return
  }

  // Process file...
}

3. Check file size

js
function handleFile(file) {
  const maxSize = 5 * 1024 * 1024 // 5MB

  if (file.size > maxSize) {
    alert('File size must be less than 5MB')
    return
  }

  // Process file...
}

4. Handle errors gracefully

js
const reader = new FileReader()

reader.onload = (e) => {
  // Success handler
}

reader.onerror = () => {
  console.error('Failed to read file:', reader.error)
  alert('Error reading file. Please try again.')
}

reader.onabort = () => {
  console.log('File reading aborted')
}

reader.readAsDataURL(file)

5. Use appropriate method for your use case

js
// Quick preview - use Object URL
function previewImage(file) {
  return showBlobPreview(img, file) // Caller owns the returned cleanup function.
}

// Upload to API - use FormData (keeps as binary)
function uploadImage(file) {
  const formData = new FormData()
  formData.append('image', file)
  fetch('/upload', { method: 'POST', body: formData })
}

// For a text-only storage interface, encode as base64
function storeImage(file) {
  const reader = new FileReader()
  reader.onload = (e) => {
    // Store e.target.result in database
  }
  reader.readAsDataURL(file)
}

Common use cases summary

Image upload preview: Use URL.createObjectURL() for instant, efficient preview File downloads: Create Blob with data, generate object URL, trigger download PDF worker setup: Bundle worker code as Blob to avoid path issues API uploads: Use FormData with File objects (no conversion needed) Storing in database: Use FileReader with base64 when binary storage isn't available

URL basics

Working with URLSearchParams

The URL interface provides powerful tools for parsing, constructing, and manipulating URLs. The searchParams property gives access to query parameters:

js
const url = new URL('https://www.google.com:443/index.html?a=1&b=2#hash')

/**
 *  URL {
 *    href: "https://www.google.com/index.html?a=1&b=2#hash",
 *    protocol: "https:",
 *    username: "",
 *    password: "",
 *    hash: "#hash",
 *    origin: "https://www.google.com", // default HTTPS port is omitted
 *    host: "www.google.com", // a non-default port would be retained
 *    hostname: "www.google.com",           // without port, without protocol
 *    port: "", // 443 is the default for HTTPS
 *    pathname: "/index.html",
 *    search: "?a=1&b=2",
 *    searchParams: URLSearchParams {}
 *  }
 */

// Read query parameters
url.searchParams.get('a') // '1'
url.searchParams.has('b') // true
url.searchParams.getAll('a') // ['1']

// Modify query parameters
url.searchParams.set('c', '3')
url.searchParams.delete('a')
url.searchParams.append('d', '4')

console.log(url.href) // Updated URL with new parameters

Use cases:

  • Reading query parameters from current page URL
  • Building URLs dynamically for API requests
  • Handling pagination, filters, and search parameters

Conclusion

Use Blob to hold binary data and File when you also need a filename and modification metadata. Choose the next step based on what the receiving API accepts: an object URL for a preview, FormData for a file upload, or text and bytes when you need to inspect the contents. Convert to base64 only when the destination requires a text representation.

Keep each object URL alive while its consumer needs it, then revoke it when the preview is removed or the worker is destroyed. This keeps the file workflow focused on the operation at hand and gives temporary URLs a clear lifetime.