How to send a file and parameters within the same XMLHttpRequest

To send a file and parameters within the same XMLHttpRequest, you can use the FormData object which allows you to construct form data including both regular parameters and file uploads.

HTML Form Setup

First, create an HTML form with a file input:

<input type="file" id="fileInput" />
<button onclick="uploadFile()">Upload</button>

<script>
function uploadFile() {
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('Please select a file');
        return;
    }
    
    sendFileWithParams(file);
}
</script>

Creating FormData with File and Parameters

Use FormData to combine regular parameters with file data:

function sendFileWithParams(file) {
    // Create FormData object
    var myForm = new FormData();
    
    // Add regular parameters
    myForm.append('param1', 'demo');
    myForm.append('param2', 6767);
    myForm.append('myDir', 'public-data');
    
    // Add the file
    myForm.append('demofile', file);
    
    // Create XMLHttpRequest
    var xhr = new XMLHttpRequest();
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                console.log('Upload successful:', xhr.responseText);
            } else {
                console.log('Upload failed:', xhr.status);
            }
        }
    };
    
    // Open and send request
    xhr.open('POST', '/upload-endpoint');
    xhr.send(myForm);
}

Complete Example with Progress Tracking

Here's a more comprehensive example with upload progress monitoring:

function uploadFileWithProgress(file) {
    var formData = new FormData();
    
    // Add parameters
    formData.append('userId', '12345');
    formData.append('category', 'documents');
    formData.append('uploadDate', new Date().toISOString());
    
    // Add file
    formData.append('file', file);
    
    var xhr = new XMLHttpRequest();
    
    // Track upload progress
    xhr.upload.onprogress = function(event) {
        if (event.lengthComputable) {
            var percentComplete = (event.loaded / event.total) * 100;
            console.log('Upload progress: ' + percentComplete.toFixed(2) + '%');
        }
    };
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            console.log('Upload completed successfully');
        } else {
            console.log('Upload failed with status: ' + xhr.status);
        }
    };
    
    xhr.onerror = function() {
        console.log('Upload failed due to network error');
    };
    
    xhr.open('POST', '/api/upload');
    xhr.send(formData);
}

Key Points

  • FormData automatically sets the correct Content-Type header with boundary
  • Don't manually set Content-Type when using FormData
  • Parameters and files are sent as multipart/form-data
  • File order in append() calls doesn't matter

Browser Compatibility

FormData is supported in all modern browsers including IE10+. For older browsers, consider using a polyfill or traditional form submission.

Conclusion

Using FormData with XMLHttpRequest provides a simple way to send both files and parameters in a single request. The browser handles the multipart encoding automatically, making file uploads straightforward.

Updated on: 2026-03-15T23:18:59+05:30

518 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements