How to Handle File Uploads with HTML5 and JavaScript? (Full Example)
HTML5 file upload can realize client preview and upload through <input type="file">, File API and FormData. 1. Use accept and multiple to limit types and multiple selections; 2. Use URL.createObjectURL to preview the image and verify the size and type; 3. Use FormData with fetch to send; 4. Use XMLHttpRequest to monitor the progress of large files.

Handling file uploads with HTML5 and JavaScript is straightforward when you use the <input type="file"> element along with the File API and FormData . You don't need a backend to preview or process files — basic validation, reading content, and sending to a server can all be done client-side.
1. Basic File Input and Selection
Start with a simple file input. Use multiple for multi-file selection and accept to restrict file types (eg, images only).
Listen for the change event to capture selected files:
document.getElementById('fileInput').addEventListener('change', function(e) {
const files = e.target.files; // FileList object
console.log(files);
});
2. Validate and Preview Files
Before uploading, check file size, type, and count. Use URL.createObjectURL() to generate preview URLs for images.
- Loop through
e.target.files— it's not an array, so useArray.from()or aforloop - Check
file.size(in bytes) — eg, reject files over 5 MB:if (file.size > 5 * 1024 * 1024) - Verify
file.typematches expected MIME types (eg,'image/jpeg') - Create previews:
const url = URL.createObjectURL(file);, then set<img src="/static/imghw/default1.png" data-src="url" class="lazy" alt="How to Handle File Uploads with HTML5 and JavaScript? (Full Example)" >
3. Upload Files with FormData and Fetch
Use FormData to package files for upload. It automatically sets the correct Content-Type ( multipart/form-data ) when sent via fetch .
const formData = new FormData();
for (const file of files) {
formData.append('files', file); // 'files' is the field name your server expects
}
fetch('/upload', {
method: 'POST',
body: formData
})
.then(res => res.json())
.then(data => console.log('Upload complete:', data));
Note: Don't set Content-Type manually — fetch does it automatically when using FormData .
4. Add Progress Tracking (Optional but Helpful)
For large files, show upload progress using the XMLHttpRequest upload.onprogress event — fetch doesn't expose progress natively.
- Create an
XMLHttpRequestinstance instead offetch - Attach
xhr.upload.onprogress = e => { const percent = (e.loaded / e.total) * 100; } - Send with
xhr.send(formData)
Basically, that's all you need to handle modern file uploads — select, validate, preview, and send — all with vanilla HTML5 and JavaScript.
The above is the detailed content of How to Handle File Uploads with HTML5 and JavaScript? (Full Example). For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20524
7
13634
4




