Blog>
Snippets

Chunked File Uploads with JavaScript

Explain how to break a large file into smaller chunks and upload these chunks sequentially to handle large file uploads efficiently.
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
Attach an event listener to the file input element to handle file selections.
function handleFileSelect(event) {
  const file = event.target.files[0];
  const chunkSize = 1048576; // 1MB chunk size
  let offset = 0;
  const fileReader = new FileReader();

  fileReader.onload = (e) => {
    uploadChunk(e.target.result, offset, file.name);
    if (offset < file.size) {
      offset += chunkSize;
      readSlice(offset);
    }
  };

  function readSlice(o) {
    const slice = file.slice(o, o + chunkSize);
    fileReader.readAsArrayBuffer(slice);
  }

  readSlice(0);
}
Handle file selection, break the selected file into chunks, and read each chunk sequentially. Uses a FileReader to read slices of the file.
async function uploadChunk(chunkData, offset, fileName) {
  const formData = new FormData();
  formData.append('chunk', chunkData);
  formData.append('fileName', fileName);
  formData.append('offset', offset);

  // Replace /upload-chunk with your server endpoint
  const response = await fetch('/upload-chunk', {
    method: 'POST',
    body: formData,
  });

  // Handle response...
  console.log(await response.text());
}
Function to upload each chunk to the server using FormData and fetch. It appends the chunk, the original file name, and the offset to the FormData before sending it to the server.