Vanilla JavaScript File Upload
Upload files with vanilla JavaScript using XMLHttpRequest for progress tracking, drag-and-drop support, file type validation, and chunked upload for large.
Code
function uploadFile(file, onProgress) {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) onProgress((e.loaded / e.total) * 100);
});
xhr.open('POST', '/api/upload');
const formData = new FormData();
formData.append('file', file);
xhr.send(formData);
return new Promise((resolve, reject) => {
xhr.onload = () => resolve(JSON.parse(xhr.responseText));
xhr.onerror = () => reject(new Error('Upload failed'));
});
}Inside the snippet
Vanilla JavaScript File Upload comes down to the function uploadFile.
A fresh value is allocated for the result; the arguments stay untouched.
Using it
The entry-point signature is function uploadFile(file, onProgress)
Key statements
return new Promise((resolve, reject) => {
xhr.onload = () => resolve(JSON.parse(xhr.responseText));
xhr.onerror = () => reject(new Error('Upload failed'));
});
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) onProgress((e.loaded / e.total) * 100);
});
FAQ
- Does `uploadFile` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `uploadFile` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.