AJAX - Resumable File Uploads Using Chunked AJAX Requests

 
 

1. Introduction

Resumable file uploads using chunked AJAX requests is a technique used in web development to upload large files to a server in smaller, manageable sections instead of transferring the entire file at once. Traditional file upload methods send the complete file in a single request. If the internet connection becomes unstable or the upload is interrupted, the user may have to restart the entire process.

Chunked file uploading solves this problem by dividing a large file into several smaller parts, commonly known as chunks. Each chunk is uploaded separately using AJAX requests. The server receives these individual parts, temporarily stores them, and combines them to reconstruct the original file after all chunks have been successfully uploaded.

The main advantage of this technique is that it allows users to resume interrupted uploads without uploading the previously completed portions again. It is particularly useful when uploading large videos, images, documents, software packages, and backup files.

2. What Is Chunked File Uploading?

Chunked file uploading is a process in which a large file is divided into smaller pieces before being transferred to a server. Each piece is treated as an individual data segment and uploaded through a separate HTTP request.

For example, consider a user uploading a file of 100 MB. Instead of sending the entire file in one request, the application can divide it into 10 chunks of 10 MB each. These chunks are transferred individually, and the server stores them until the complete file is received.

JavaScript provides the Blob.slice() method to divide files into smaller sections. The File API allows developers to access and process these sections directly in the browser.

AJAX makes it possible to transfer each chunk asynchronously without refreshing the webpage. This allows users to continue interacting with the application while the upload is in progress.

3. How Resumable File Uploads Work

The resumable upload process involves several important stages.

Step 1: Selecting the File

The user selects a file through an HTML file input element. JavaScript accesses the selected file using the browser's File API. The application identifies the file name, size, and type before beginning the upload.

Step 2: Dividing the File into Chunks

The selected file is divided into smaller sections using the Blob.slice() method. The developer determines the appropriate chunk size depending on the application requirements and server limitations.

For example, a 50 MB file can be divided into ten chunks of 5 MB each.

Step 3: Sending Chunks Through AJAX

Each chunk is transferred to the server through an individual AJAX request. The application can use the XMLHttpRequest object or the Fetch API to send the data.

Every request should include relevant information, such as the file identifier, chunk number, total number of chunks, and upload session identifier. This information helps the server identify the correct position of each chunk.

Step 4: Receiving and Storing Chunks

The server receives each chunk and stores it temporarily. It maintains information about which chunks have been received successfully and which are still pending.

This information is important because the server must identify missing chunks if the upload is interrupted.

Step 5: Handling Upload Interruption

Sometimes, an upload may stop because of an internet connection failure, browser closure, server interruption, or unexpected application error.

Instead of starting again from the beginning, the application can contact the server to identify the chunks that have already been received.

The application then uploads only the missing chunks.

Step 6: Reassembling the Original File

After receiving all the chunks, the server combines them in the correct sequence to reconstruct the original file.

The server verifies the completed file and makes it available for further processing or downloading.

4. Role of AJAX in Resumable File Uploads

AJAX plays an important role in implementing resumable file uploads because it allows data to be transferred between the browser and server without reloading the webpage.

Using AJAX, developers can upload individual chunks independently and receive responses from the server after each transfer.

The XMLHttpRequest object provides useful features for monitoring upload progress through its upload.onprogress event. Developers can use this information to display the percentage of the file that has been uploaded.

For example, if a user uploads a 100 MB file and 60 MB has been successfully transferred, the application can display 60% upload progress.

AJAX also allows developers to handle server responses, identify failed requests, retry unsuccessful chunks, and update the upload interface dynamically.

5. Example of Chunked File Uploading Using JavaScript

The following example demonstrates how a file can be divided into smaller sections and uploaded individually using the Fetch API.

async function uploadFile(file) {
    const chunkSize = 5 * 1024 * 1024;
    const totalChunks = Math.ceil(file.size / chunkSize);

    const fileId = crypto.randomUUID();

    for (let i = 0; i < totalChunks; i++) {
        const start = i * chunkSize;
        const end = Math.min(start + chunkSize, file.size);

        const chunk = file.slice(start, end);

        const formData = new FormData();

        formData.append("file", chunk);
        formData.append("fileId", fileId);
        formData.append("chunkNumber", i);
        formData.append("totalChunks", totalChunks);

        const response = await fetch("/upload", {
            method: "POST",
            body: formData
        });

        if (!response.ok) {
            throw new Error("Chunk upload failed");
        }
    }

    console.log("File uploaded successfully");
}

In this example, the file is divided into chunks of 5 MB each. The Math.ceil() function calculates the total number of chunks required to upload the complete file.

The Blob.slice() method extracts the required portion of the original file. Each extracted chunk is added to a FormData object and sent to the server through a separate Fetch request.

The server uses the file identifier and chunk number to store the received data in the correct location.

This is a basic sequential chunk-upload example. To make it fully resumable, the application must also implement server-side upload-session management, a mechanism to retrieve previously received chunk numbers, and a completion request to combine the chunks.

6. Implementing Upload Progress Tracking

Progress tracking helps users understand how much of a file has been transferred to the server.

Developers can calculate upload progress by comparing the total number of successfully uploaded bytes with the original file size.

For example, if the original file size is 200 MB and 100 MB has been successfully uploaded, the progress is 50%.

The XMLHttpRequest object provides an upload progress event that can be used to monitor the transfer of individual chunks.

const xhr = new XMLHttpRequest();

xhr.open("POST", "/upload", true);

xhr.upload.onprogress = function(event) {
    if (event.lengthComputable) {
        const percentage =
            (event.loaded / event.total) * 100;

        console.log(
            "Chunk Upload Progress: " +
            percentage.toFixed(2) + "%"
        );
    }
};

xhr.send(formData);

When uploading multiple chunks, the application should combine the progress of completed chunks with the progress of the currently uploading chunk to calculate the overall file upload percentage.

This provides users with accurate information about the entire upload process.

7. Advantages of Resumable File Uploads

Resumable file uploads provide several benefits for modern web applications.

  1. Improved Reliability: If an upload is interrupted, users can continue from the last successfully uploaded chunk rather than restarting the entire process.

  2. Efficient Data Transfer: Only the missing portions of a file need to be transferred again, reducing unnecessary data usage.

  3. Better User Experience: Users can monitor upload progress and avoid losing previously completed upload work.

  4. Support for Large Files: Large videos, high-resolution images, software packages, and backup files can be transferred in smaller sections.

  5. Reduced Upload Failure Impact: Temporary network interruptions affect only the current or unsuccessful chunks rather than the entire file.

  6. Flexible Upload Management: Developers can implement retry mechanisms, upload limits, progress indicators, and parallel chunk transfers according to application requirements.

8. Challenges and Limitations

Although resumable file uploads provide several advantages, developers must consider certain challenges while implementing this technique.

Server-Side Management: The server must maintain upload session information and identify the chunks received successfully. Without proper management, chunks may be lost or stored incorrectly.

Temporary Storage Requirements: The server needs sufficient storage space to hold incomplete files until all chunks are received and combined.

Chunk Ordering: Every chunk must be identified and assembled in its original sequence. Incorrect ordering can result in a corrupted file.

Network Failures: Individual chunk uploads may fail because of unstable internet connections. Developers must implement retry mechanisms to handle such situations.

Security Considerations: The server must validate uploaded files, restrict file sizes, verify permissions, and prevent unauthorized access to upload sessions. It should also verify the integrity of the reconstructed file.

Resource Management: Upload sessions that remain incomplete for long periods can consume server storage. Applications should implement expiration rules and remove abandoned temporary chunks.

9. Real-World Applications

Resumable file uploads are widely used in applications that handle large amounts of user-generated content.

  • Cloud Storage Platforms: Services such as Google Drive and Dropbox use resumable upload techniques to improve the reliability of large file transfers.

  • Video Sharing Platforms: Users can upload large video files without having to restart the entire transfer after a temporary network interruption.

  • Educational Platforms: Students and teachers can upload assignments, recorded lectures, presentations, and other large learning materials.

  • Enterprise Applications: Businesses can transfer large reports, databases, backup files, and other important documents.

  • Media Management Systems: Photography and video production applications can upload high-resolution media files efficiently.

10. Conclusion

Resumable file uploads using chunked AJAX requests is an important technique for developing reliable and efficient web applications. By dividing large files into smaller sections and transferring them through individual asynchronous requests, developers can reduce the impact of network interruptions and improve the overall upload experience.

The combination of JavaScript File API, Blob slicing, AJAX requests, server-side session management, and progress tracking makes it possible to build flexible file upload systems. The ability to identify previously uploaded chunks and transfer only the missing portions makes this technique especially useful for applications that handle large files.

Therefore, resumable chunked file uploading is a valuable approach in modern web development, particularly for cloud storage, educational platforms, media sharing services, and enterprise applications.