search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
1. Basic File Input and Selection
2. Validate and Preview Files
3. Upload Files with FormData and Fetch
4. Add Progress Tracking (Optional but Helpful)
Home Web Front-end H5 Tutorial How to Handle File Uploads with HTML5 and JavaScript? (Full Example)

How to Handle File Uploads with HTML5 and JavaScript? (Full Example)

Dec 25, 2025 am 06:04 AM

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.

How to Handle File Uploads with HTML5 and JavaScript? (Full Example)

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 use Array.from() or a for loop
  • Check file.size (in bytes) — eg, reject files over 5 MB: if (file.size &gt; 5 * 1024 * 1024)
  • Verify file.type matches 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 XMLHttpRequest instance instead of fetch
  • Attach xhr.upload.onprogress = e =&gt; { 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)