Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
-
FormDataautomatically sets the correctContent-Typeheader with boundary - Don't manually set
Content-Typewhen usingFormData - 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.
