HTML File Input: input type=file Attributes and Styling

HTML File Input: input type=file Attributes and Styling

17 min read
Static Forms Team
htmlformsfile uploadaccessibility
Share:

The HTML file input is one line of markup, <input type="file">, and it is still easy to get wrong. The file never reaches the server because the form has the wrong enctype. The accept filter gets treated as security. The value reads C:\fakepath\photo.jpg. A custom "Upload" button works with a mouse and does nothing with a keyboard.

This reference covers the element itself: every attribute that changes how the picker behaves, how to read the selected files in JavaScript, and how to style the control without breaking it for keyboard and screen reader users. The facts come from MDN's file input reference, checked on 31 October 2026.

If you want the whole path from form to inbox (markup, backend, storage, email), the end-to-end HTML file upload guide covers it. We make Static Forms, a form backend that accepts file uploads (Starter and up), and the example near the end posts to it, but everything before that works with any server.

What `` does

A file input opens the operating system's file chooser. The files the visitor picks become a FileList on the element's files property. When the form submits, the browser sends each file's bytes in the request body.

Two things have to be right for the bytes to leave the browser:

  • The form needs enctype="multipart/form-data" and method="post". With the default encoding, the browser sends the file name and nothing else.
  • The input needs a name. Like any field, an input without a name is left out of the submission entirely.

The minimum reliable markup is a labeled input inside a multipart form:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Minimal file input</title>
</head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <label for="resume">Your CV (PDF)</label>
    <input id="resume" name="resume" type="file" accept=".pdf" required>
    <button type="submit">Send</button>
  </form>
</body>
</html>

Replace /upload with whatever endpoint receives the form.

input type=file attributes at a glance

These are the attributes that change how a file input behaves. The general form attributes (name, id, disabled, form) work as they do on any input.

Attribute What it does Example Caveat
accept Hints which file types the chooser should offer: extensions, MIME types, or image/*, audio/*, video/* accept="image/*,.pdf" Not validation. Visitors can switch the chooser to "all files".
multiple Lets the visitor select more than one file multiple Your JavaScript has to loop over files, not read files[0].
capture Asks for the user-facing (user) or outward-facing (environment) camera or microphone capture="environment" Limited availability. On desktop you get the normal file chooser.
required Blocks submission until at least one file is selected required Says nothing about type or size.
webkitdirectory Selects a whole folder instead of individual files webkitdirectory Baseline only since August 2025, so older browsers ignore it.

Two properties matter as much as the attributes. files holds the selected File objects, each with name, size, type and lastModified. value holds only a display string, covered below.

What `accept` does, and what it does not do

accept takes a comma-separated list of what MDN calls unique file type specifiers. Each one is a file extension starting with a period (.pdf, .docx), a MIME type (application/pdf), or one of the wildcards image/*, audio/* and video/*.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>accept examples</title>
</head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <label for="avatar">Profile photo</label>
    <input id="avatar" name="avatar" type="file" accept="image/png, image/jpeg, image/webp">

    <label for="receipt">Receipt (photo or PDF)</label>
    <input id="receipt" name="receipt" type="file" accept="image/*,.pdf">

    <label for="cv">CV</label>
    <input id="cv" name="cv" type="file" accept=".pdf,.doc,.docx">

    <button type="submit">Upload</button>
  </form>
</body>
</html>

MDN says: accept "doesn't validate the types of the selected files; it provides hints for browsers". Most choosers have an option to show all files, and a visitor who picks a .zip gets a .zip into your form. Pair it with a JavaScript check for a fast error message and a server check for the real decision. Why the input accept attribute doesn't validate file types shows the bypass and the extension, file.type and signature checks that do work.

capture opens the camera on phones

capture="user" asks for the front camera, capture="environment" for the rear one. It only applies when accept asks for images, video or audio. MDN marks it as limited availability and notes that on a desktop computer "you'll likely get a typical file picker". Treat it as a shortcut for phone users, never as the only way to provide a file.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Photo of the damage</title>
</head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <label for="damage-photo">Photo of the damage</label>
    <input id="damage-photo" name="damagePhoto" type="file" accept="image/*" capture="environment">
    <button type="submit">Send photo</button>
  </form>
</body>
</html>

capture used to be a boolean attribute. Older code with a bare capture still works where it is supported, but give it a value in new markup.

webkitdirectory picks a whole folder

With webkitdirectory, the chooser selects a folder, and files gets one File for every file inside it, subfolders included. The list is flat, so each file carries a webkitRelativePath, a path from the chosen folder such as PhotoAlbums/Birthdays/PIC2343.jpg, to tell you where it sat. The prefix is a leftover from its origin as a Chrome API; MDN lists it as Baseline 2025, newly available since August 2025.

A folder can hold hundreds of files and far more bytes than a form backend accepts in one request, so show the count and total size before anything is sent. The demo in the next section does that.

The `C:\fakepath\` surprise

Read input.value after picking report.pdf and you get C:\fakepath\report.pdf, on every operating system. Browsers hide the real path so a page can't learn how your disk is organised. With several files selected, value only describes the first one.

Never parse value. Read files instead. A script also can't set a file input's value to a file, so you can't point it at a path. You can clear it with input.value = '', or assign a FileList you already hold, for example one from a drop event. Why JavaScript can't set a file input's value explains the rule and shows code for each fix. The form input types reference shows how file compares with the other 21 input types.

Handling Files Client Side with the JavaScript File API

Everything useful about a selection lives on input.files. It behaves like an array: check length, index into it, or turn it into a real array with Array.from().

Reading selected files

Listen for change. It fires after the chooser closes with a new selection. MDN notes that closing the chooser without a change, or picking the same files again, fires cancel instead, so clear the input after handling it if the visitor may need to pick the same file twice.

Client-side validation that improves UX

A quick check in the browser saves the visitor a failed upload: is each file a type you take, and does the selection fit your size limit? Check file.type and file.size and show the message next to the field.

file.type is whatever the visitor's browser reports, so a renamed file can pass. That's fine for a friendly error, and it's why the server checks again.

Building an image preview

URL.createObjectURL(file) gives you a temporary URL for an <img>. Revoke it with URL.revokeObjectURL() when the selection changes, or each preview keeps its file in memory until the page closes. You don't need to read the whole file into a data URL with FileReader just to show it.

A better multi-file UI

With several files, the native control shows little more than a count. With multiple or webkitdirectory, list each file's name and size and the total, so the visitor can see a wrong file before sending it. Keep the list in an element with aria-live="polite" so screen reader users hear the update.

The demo below reads the selection, rejects wrong types and oversized totals, previews the first image, and lists every file.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File input with validation, preview and file list</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 560px; margin: 2rem auto; padding: 0 1rem; }
    .error { color: #b42318; }
    #preview { display: block; max-width: 200px; margin-top: 1rem; border-radius: 6px; }
    #preview[hidden] { display: none; }
  </style>
</head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <label for="files">Photos or PDFs (up to 4 MB in total)</label>
    <input id="files" name="files" type="file" multiple accept="image/jpeg,image/png,image/webp,application/pdf"
      aria-describedby="file-error file-summary">
    <p id="file-error" class="error" role="alert"></p>
    <div id="file-summary" aria-live="polite"></div>
    <img id="preview" alt="Preview of the first selected image" hidden>
    <button type="submit">Upload</button>
  </form>

  <script>
    const input = document.getElementById('files');
    const error = document.getElementById('file-error');
    const summary = document.getElementById('file-summary');
    const preview = document.getElementById('preview');

    const allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'application/pdf'];
    const maxTotalBytes = 4 * 1024 * 1024;
    let previewUrl = null;

    function formatSize(bytes) {
      if (bytes < 1024 * 1024) return Math.round(bytes / 1024) + ' KB';
      return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
    }

    function clearPreview() {
      if (previewUrl) URL.revokeObjectURL(previewUrl);
      previewUrl = null;
      preview.hidden = true;
      preview.removeAttribute('src');
    }

    input.addEventListener('change', () => {
      const files = Array.from(input.files);
      error.textContent = '';
      summary.textContent = '';
      clearPreview();

      const wrongType = files.find((file) => !allowedTypes.includes(file.type));
      if (wrongType) {
        error.textContent = wrongType.name + ' is not a JPEG, PNG, WebP or PDF file.';
        input.value = '';
        return;
      }

      const total = files.reduce((sum, file) => sum + file.size, 0);
      if (total > maxTotalBytes) {
        error.textContent = 'These files add up to ' + formatSize(total) + '. The limit is 4 MB in total.';
        input.value = '';
        return;
      }

      if (files.length > 0) {
        const list = document.createElement('ul');
        for (const file of files) {
          const item = document.createElement('li');
          item.textContent = file.name + ' (' + formatSize(file.size) + ')';
          list.append(item);
        }
        const heading = document.createElement('p');
        heading.textContent = files.length + ' file(s) selected, ' + formatSize(total) + ' in total:';
        summary.append(heading, list);
      }

      const firstImage = files.find((file) => file.type.startsWith('image/'));
      if (firstImage) {
        previewUrl = URL.createObjectURL(firstImage);
        preview.src = previewUrl;
        preview.hidden = false;
      }
    });
  </script>
</body>
</html>

Clear the input on an error, or the rejected file goes out with the next submit.

Building Accessible and Custom Styled File Inputs

The default control looks different in every browser, so most designs restyle it. Most of the accessibility bugs around file inputs come from how that restyling is done.

Style the native button with ::file-selector-button

You may not need a custom control at all. The ::file-selector-button pseudo-element targets the "Choose file" button inside the input, and MDN lists it as widely available since April 2021. The input stays a real input, so keyboard focus, screen reader names and form submission keep working.

One catch from MDN: the button is a whole element with its own browser styles, so fonts and colours "won't necessarily inherit" from the input. Set them explicitly.

What not to do

The common pattern hides the input with display: none (or visibility: hidden) and puts a <button> next to it that calls input.click(). MDN warns that assistive technology takes both styles to mean the input isn't interactive. The visible button also has no link to the field's label, its error message or its required state.

The label pattern that holds up

When you need a fully custom look, keep the real input on the page and make it invisible with opacity: 0, which MDN recommends for exactly this reason. Wrap it in a <label> styled as the button. Clicking the label opens the chooser, and Tab still lands on the real input. Use :focus-within on the label to draw the focus ring the invisible input can't show.

Here are both approaches side by side:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Accessible styled file inputs</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 560px; margin: 2rem auto; padding: 0 1rem; }
    .field { margin-bottom: 2rem; }

    /* Approach 1: keep the native control, restyle its button */
    input[type="file"].native::file-selector-button {
      font: inherit;
      color: #ffffff;
      background: #1f2937;
      border: 0;
      border-radius: 6px;
      padding: 0.5rem 1rem;
      margin-right: 0.75rem;
      cursor: pointer;
    }
    input[type="file"].native::file-selector-button:hover { background: #374151; }
    input[type="file"].native:focus-visible { outline: 3px solid #fe5b5b; outline-offset: 3px; }

    /* Approach 2: label styled as a button, real input on top with opacity 0 */
    .picker {
      position: relative;
      display: inline-flex;
      align-items: center;
      padding: 0.6rem 1.1rem;
      border: 2px dashed #9ca3af;
      border-radius: 8px;
      cursor: pointer;
    }
    .picker input {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
      cursor: pointer;
    }
    .picker:focus-within { outline: 3px solid #fe5b5b; outline-offset: 3px; }
    .picker:hover { border-color: #1f2937; }
    .file-name { margin-left: 0.75rem; color: #4b5563; }
  </style>
</head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <div class="field">
      <label for="attachment">Attachment</label><br>
      <input class="native" id="attachment" name="attachment" type="file">
    </div>

    <div class="field">
      <label class="picker">
        <span>Choose portfolio files</span>
        <input id="portfolio" name="portfolio" type="file" multiple aria-describedby="portfolio-names">
      </label>
      <span id="portfolio-names" class="file-name" aria-live="polite">No files chosen</span>
    </div>

    <button type="submit">Send</button>
  </form>

  <script>
    const portfolio = document.getElementById('portfolio');
    const names = document.getElementById('portfolio-names');

    portfolio.addEventListener('change', () => {
      const count = portfolio.files.length;
      if (count === 0) names.textContent = 'No files chosen';
      else if (count === 1) names.textContent = portfolio.files[0].name;
      else names.textContent = count + ' files chosen';
    });
  </script>
</body>
</html>

Because the invisible input covers the whole label, a click anywhere on it lands on the real control. The visible file name lives in an element the input points to with aria-describedby, so it is read out with the field.

Keyboard and screen reader checks before you ship

Test it without a mouse:

  • Tab reaches the control, and you can see where focus is.
  • Space or Enter opens the chooser.
  • A screen reader announces the field's label and that it is a file upload control, then the chosen file names.
  • Submitting a required input with no file shows the browser's message next to it.
  • At 200% zoom and on a narrow phone screen, the button and file name don't overlap.

Security: what the browser can't enforce

Browser checks give honest visitors a quick error; they don't stop anyone sending a request directly. The server makes the real decisions:

  • Type. Check the file's contents or at least its extension and declared type on the server. accept and file.type are both under the visitor's control.
  • Size. Set a limit for the whole request on the server. The browser check exists to give a readable error before a long upload fails.
  • Names. Treat file.name as untrusted text. Don't use it as a storage path or drop it into HTML unescaped.
  • What you keep. Decide how long uploaded files stay and who can open them before the first one arrives.

How a file travels from an HTML file input to the server: the visitor picks files, the input exposes them as a FileList, JavaScript checks type and total size for a quick error, the form sends multipart/form-data, and the server checks type and size again before keeping the file

Integrating File Uploads into Modern Web Stacks

The contract is the same in every framework: a file input with a name, a multipart request, and a server that reads it. Frameworks only change how you get there.

React component pattern

In React, leave the file input uncontrolled. You can't put a File into value, so don't bind it to state. Read event.target.files in the change handler and build FormData from the form when it submits. fetch sets the multipart Content-Type and boundary itself when the body is FormData, so don't set that header.

JSX
import { useState } from 'react';

const ALLOWED_TYPES = ['application/pdf', 'image/jpeg', 'image/png'];

export default function UploadForm() {
  const [fileName, setFileName] = useState('');
  const [error, setError] = useState('');
  const [status, setStatus] = useState('');

  function handleFileChange(event) {
    const file = event.target.files[0];
    setError('');
    setFileName('');
    if (!file) return;
    if (!ALLOWED_TYPES.includes(file.type)) {
      setError('Please choose a PDF, JPEG or PNG file.');
      event.target.value = '';
      return;
    }
    setFileName(file.name);
  }

  async function handleSubmit(event) {
    event.preventDefault();
    setStatus('Uploading...');
    try {
      const response = await fetch('/upload', {
        method: 'POST',
        body: new FormData(event.currentTarget),
      });
      setStatus(response.ok ? 'Uploaded.' : 'Upload failed (' + response.status + ').');
    } catch {
      setStatus('Upload failed. Check your connection and try again.');
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="document">Document</label>
      <input
        id="document"
        name="document"
        type="file"
        accept=".pdf,image/jpeg,image/png"
        onChange={handleFileChange}
        aria-describedby="document-help"
        required
      />
      <p id="document-help">{fileName || 'PDF, JPEG or PNG'}</p>
      <p role="alert">{error}</p>
      <button type="submit">Upload</button>
      <p role="status">{status}</p>
    </form>
  );
}

Point the fetch URL at your own route handler or a hosted form backend. The end-to-end upload guide has versions for Next.js and other stacks.

Complete Working Example

The example below sends a short application with a CV to Static Forms, which forwards each submission by email with the files attached. File uploads are Starter and up. A submission is limited to 4.5 MB in total, files and fields together, so the page refuses anything over 4 MB before it sends. Replace YOUR_API_KEY with the key from your form's settings and redirectTo with a full URL on your site.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Apply</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 560px; margin: 2rem auto; padding: 0 1rem; }
    label { display: block; font-weight: 600; margin-top: 1rem; }
    input[type="text"], input[type="email"] { width: 100%; box-sizing: border-box; padding: 0.6rem; font-size: 1rem; }
    input[type="file"]::file-selector-button {
      font: inherit; color: #ffffff; background: #1f2937; border: 0;
      border-radius: 6px; padding: 0.5rem 1rem; margin-right: 0.75rem; cursor: pointer;
    }
    input[type="file"]:focus-visible { outline: 3px solid #fe5b5b; outline-offset: 3px; }
    .hint { color: #4b5563; font-size: 0.9rem; }
    .error { color: #b42318; }
    button { margin-top: 1.5rem; padding: 0.75rem 1.5rem; font-size: 1rem; }
  </style>
</head>
<body>
  <h1>Apply</h1>
  <form id="apply" action="https://api.staticforms.dev/submit" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="apiKey" value="YOUR_API_KEY">
    <input type="hidden" name="subject" value="New application">
    <input type="hidden" name="redirectTo" value="https://example.com/thank-you.html">

    <label for="name">Name</label>
    <input id="name" name="name" type="text" required autocomplete="name">

    <label for="email">Email</label>
    <input id="email" name="email" type="email" required autocomplete="email">

    <label for="cv">CV (PDF or Word)</label>
    <input id="cv" name="cv" type="file" required accept=".pdf,.doc,.docx" aria-describedby="cv-hint cv-error">
    <p id="cv-hint" class="hint">PDF, DOC or DOCX, up to 4 MB.</p>
    <p id="cv-error" class="error" role="alert"></p>

    <button type="submit">Send application</button>
  </form>

  <script>
    const form = document.getElementById('apply');
    const cv = document.getElementById('cv');
    const cvError = document.getElementById('cv-error');
    const allowed = ['.pdf', '.doc', '.docx'];

    form.addEventListener('submit', (event) => {
      cvError.textContent = '';
      const file = cv.files[0];
      if (!file) return;

      const name = file.name.toLowerCase();
      if (!allowed.some((ext) => name.endsWith(ext))) {
        event.preventDefault();
        cvError.textContent = 'Please upload a PDF or Word document.';
        return;
      }
      if (file.size > 4 * 1024 * 1024) {
        event.preventDefault();
        cvError.textContent = 'Your CV is larger than 4 MB. Please send a smaller file.';
      }
    });
  </script>
</body>
</html>

The size check runs on submit because a request over 4.5 MB is rejected before Static Forms sees it, and a plain HTML form then shows a hosting error page instead of your thank-you page. The email field doubles as the reply-to address, so you can answer an applicant from your inbox. The file uploads docs cover the limit, multiple files and where uploaded files are stored.

Troubleshooting Common HTML File Input Problems

What you see Why, and what to do
Only the file name reaches the server The form is missing enctype="multipart/form-data" or method="post".
The file field is missing from the request The input has no name attribute.
Only one of several files arrives Check for multiple on the input, and that your script loops over files instead of reading files[0].
The path reads C:\fakepath\... Expected. Browsers hide real paths. Read input.files.
The browser accepted a file the server rejects accept is a hint, and the two rule sets differ. Define the allowed types and size once and apply them in both places.
Picking the same file again does nothing No change event fires for an unchanged selection. Clear the input with input.value = '' after you handle it.
The custom upload button ignores the keyboard The input is hidden with display: none or visibility: hidden. Use opacity: 0 on the real input, or style it with ::file-selector-button.
capture opens a normal file chooser You are on a desktop, or the browser doesn't support capture. Nothing to fix.
A framework form loses the file The input remounted (a changed key or a component that unmounts) or form.reset() ran. Keep the input mounted with a stable key, and read files in the change handler.

FAQ

How do I let users select multiple files?

Add the multiple attribute: <input type="file" name="photos" multiple>. The selection arrives in input.files as a list, and the form sends every file under the same field name.

How do I restrict a file input to images or PDFs?

Use accept="image/*,.pdf" to filter the chooser, then check file.type or the extension in JavaScript for a quick error, and check again on the server. accept alone doesn't stop other files.

Can I set the value of a file input with JavaScript?

Not to a path. For security, a script can't choose a file from the visitor's disk. It can clear the selection with input.value = '', or assign a FileList it already holds, for example from drag and drop.

How do I style input type=file?

Style the built-in button with ::file-selector-button, or wrap the input in a <label> styled as a button and make the input opacity: 0. Don't use display: none, which removes the input from keyboard and screen reader use.

Send the files somewhere

A file input only gets the file as far as the request. To receive uploads on a static site without running a server, point the form at https://api.staticforms.dev/submit with your apiKey; the file uploads docs list the limits and storage per plan, and the quick start gets a first form working.